why strsep segment fault

2.9k views Asked by At
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
  char *buf = "2012/9/8";
  char sep[] = "/";
  char *token;
//  char *bp = strdup(buf);
  char *bp = buf;
  while ((token = strsep(&bp,sep))) {
    printf("tok = `%s'\n", token);
  }
  free(bp);
  return 0;
}

If I don't use strdup. assign "char *bp = buf". then the above programe will segment fault. gdb output below:

Program terminated with signal 11, Segmentation fault.
#0  0x00007fcc949c13b5 in strsep () from /lib/x86_64-linux-gnu/libc.so.6
(gdb) bt
#0  0x00007fcc949c13b5 in strsep () from /lib/x86_64-linux-gnu/libc.so.6
#1  0x00000000004005d5 in main () at str_split.c:11

what's wrong with the program ?

1

There are 1 answers

2
cnicutar On BEST ANSWER

If I don't use strdup. assign "char *bp = buf". then the above programe will segment fault.

It might have to to something with buf pointing to memory which cannot be legally written, a string literal in this case. If you use strdup you'll be writing to your own writable copy.