简体   繁体   English

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

[英]String to vector in C, Program received signal SIGSEGV, Segmentation fault

I write a simple function to make a C string (NOT C++) to a vector for function execvp in Linux. 我编写了一个简单的函数,将C字符串(NOT C ++)转换为Linux中函数execvp的向量。

This is my code: 这是我的代码:

#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;
}

When I run it, I it'get Segmentation fault . 当我运行它时,我得到了Segmentation fault

Then I debug it, I just found, When run 然后我调试它,我刚发现,运行时

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

Program received signal SIGSEGV, Segmentation fault. 程序收到信号SIGSEGV,分段故障。

at that time *flag = ' ' 当时*flag = ' '

I couldn't unstand why program received signal SIGSEGV when program change cstring 我无法理解为什么程序更改cstring时程序会收到信号SIGSEGV

char *p = "This is a BUG";

is a string literal and it's undefined behavior to modify it. 是字符串文字,修改它是未定义的行为 char *flag = cstring; means flag points to the same location (which happens to be read-only memory) as p . 表示flag指向与p相同的位置(恰好是只读存储器)。 What you're attempting to do (as it is now) is illegal. 您正在尝试做的事情(现在如此)是非法的。

Try with 试试吧

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

The cause of getting SIGSEGV is that "This is the bug" string was placed into const section. 获得SIGSEGV的原因是将"This is the bug"字符串放置在const节中。 When program is loaded corresponding memory area is marked read-only. 程序加载后,相应的存储区被标记为只读。 When program tries to write to read-only memory area it receives segmentation fault. 当程序尝试写入只读存储区时,它将收到分段错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM