简体   繁体   中英

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.

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 .

Then I debug it, I just found, When run

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

Program received signal SIGSEGV, Segmentation fault.

at that time *flag = ' '

I couldn't unstand why program received signal SIGSEGV when program change cstring

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 . 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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