字符串转换为C中的矢量,程序接收信号SIGSEGV,分段错误

字符串转换为C中的矢量,程序接收信号SIGSEGV,分段错误,c,string,pointers,memory-management,segmentation-fault,C,String,Pointers,Memory Management,Segmentation Fault,我编写了一个简单的函数,在Linux中为函数execvp生成一个C字符串(不是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

我编写了一个简单的函数,在Linux中为函数
execvp
生成一个
C
字符串(不是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;
}
#包括
#包括
#包括
字符**矢量化(字符*cstring){
int w_count=0;//字数
char*flag=cstring;
而(*标志!='\0'){
如果(*标志==''| |*标志=='\n'| |*标志=='\t')
*标志='\0';
flag++;
否则{
w_count++;
而(*flag!=''&&*flag!='\n'&&*flag!='\t'&&*flag!='\0')
flag++;
}
}
char**cvector=(char**)malloc(sizeof(char*)*(w_count+1));
cvector[w_count]=NULL;
int v_count;//向量计数
对于(v_count=0,flag=cstring;v_count
当我运行它时,我得到了
分段错误

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

*标志='\0'//(第12行)

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

当时
*标志=''

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

char *p = "This is a BUG";
是字符串文字,修改它是未定义的行为<代码>字符*标志=cstring
表示
标志
指向与
p
相同的位置(恰好是只读存储器)。你试图做的事情(就像现在一样)是非法的

试一试

char p[] = "This is a BUG"; 

获取SIGSEGV的原因是
“这是错误”
字符串被放入const部分。当加载程序时,相应的内存区域被标记为只读。当程序试图写入只读内存区域时,它会收到分段错误。

在过去,由于文本字符串在内存中未标记为只读,所以可以修改。现在的编译器将存储文字字符串的内存标记为只读,因此无论您是否尝试修改它,都会得到SEGFULT。@nhahtdh真的吗?你有这方面的参考资料吗?标准说这是未定义的行为,我更倾向于相信它。@nhahtdh同样,未定义的行为意味着任何事情都可能发生。它不需要崩溃。你过去是什么意思?你是说十年前?因为C++03和C++11都说这是UB。不知道以前的版本,但这应该足够了。它不需要崩溃,但通常实现为只读,并且在修改时崩溃:。我从我的教授那里听说,过去可以修改文本字符串,因为它不是只读的。你能对你的帖子稍作修改,这样我就可以删除否决票了吗?@nhahdh为了将来,请保留否决票,以备答案明显有缺陷时使用。如果他们有确凿的理由,我不会反对他们