字符串到C中的向量,程序接收信号SIGSEGV,分段故障

thl*_*ood 2 c string pointers memory-management segmentation-fault

我编写了一个简单的函数来CexecvpLinux中的函数生成一个字符串(NOT C++).

这是我的代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char** vecting(char *cstring) {

    int w_count = 0;           //word count
    char *flag = cstring;

    while (*flag != '\0') {
        if (*flag == ' ' || *flag == '\n' || *flag == '\t')
            *flag = '\0';
            flag++;
        else {
            w_count++;
            while (*flag != ' ' && *flag != '\n' && *flag != '\t' && *flag != '\0')
                flag++;
        }
    }

    char **cvector = (char **)malloc(sizeof(char *)*(w_count+1));
    cvector[w_count] = NULL;
    int v_count;                //vector count

    for (v_count = 0, flag = cstring; v_count < w_count; v_count++) {
        while (*flag == '\0')
            flag++;
        cvector[v_count] = flag;
        while (*flag != '\0')
            flag++;
    }
    return cvector;
}

int main()
{
    char *p = "This is a BUG";
    char **argv = vecting(p);
    char **temp;

    for (temp = argv; *temp != NULL; temp++)
        printf("%s\n", *temp);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我运行它时,它就是它Segmentation fault.

然后我调试它,我刚刚发现,运行时

*flag = '\0'; //(in line 12)

程序接收信号SIGSEGV,分段故障.

那时候 *flag = ' '

我无法理解为什么程序在程序改变时收到信号SIGSEGV cstring

Luc*_*ore 6

char *p = "This is a BUG";
Run Code Online (Sandbox Code Playgroud)

是一个字符串文字,它是修改它的未定义行为.char *flag = cstring;表示flag指向同一位置(恰好是只读存储器)p.你试图做的事情(现在是这样)是非法的.

试试吧

char p[] = "This is a BUG"; 
Run Code Online (Sandbox Code Playgroud)