0

I wanna split a string by '/' and change char '/' to '/0' in the string, so I wrote a function like this:

void parse_query(char* str){
    char* p = str;
    char** r = (char**)malloc(sizeof(char*)*5);
    int i = 0;
    r[i++] = p;
    while(p=strchr(p,'/')){
        *p = '/0';
        p++;
        r[i++] = p;
    }
}

When I ran the program like below:

char* s = "a/b";
parse_query(s);

the segmentation fault occurred at this line:

*p = '/0';

Can anyone give me a suggestion?

Jerry
  • 121
  • 1
  • 2
  • 10
  • 1
    Are you trying to change one character to 2 ('/' to "/0"), or change it to a zero character ('\0')? – AntonH Jun 19 '14 at 13:51
  • [Please don't cast the return value of `malloc()` in C](http://stackoverflow.com/a/605858/28169). – unwind Jun 19 '14 at 13:57

3 Answers3

4
When I ran the program like below:

char* s = "a/b";

So you are modifying the string literal "a/b", which is undefined behaviour. If you want to modify it, then use an array like this:

char s[] = "a/b";
parse_query(s);

In addition, you should do (as noted by AntonH):

*p = '\0'; 

or
*p = 0;

to terminate the string. '/0' is the different from '\0'.

P.P
  • 117,907
  • 20
  • 175
  • 238
1

Replace:

*p = '/0';

which is not actually one character, but two, with:

*p = '\0';

Which is replacing the value pointed to by p with a value of zero. Which is what I believe you want.

AntonH
  • 6,359
  • 2
  • 30
  • 40
0

Apart from the fact that it should be '\0', I think the segmentation fault stems from the fact that the string "a/b" is a literal, and these are generally stored in read-only memory. This means you probably can't write to that memory, and if you try, you get a segmentation fault.

Make a copy of the literal string into a writeable buffer and try it on that. I bet it works then.

Rudy Velthuis
  • 28,387
  • 5
  • 46
  • 94