2
#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 ?

cnicutar
  • 178,505
  • 25
  • 365
  • 392
youhong
  • 33
  • 1
  • 4

1 Answers1

4

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.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • 1
    char *buf = "2012/9/8"; is const string,If I declar buf as :char buf[] = "2012/9/8".Then it does work. – youhong Aug 13 '12 at 01:41
  • For information on why a string literal isn't writable memory, I found [this answer](https://stackoverflow.com/a/164258/3684433) to be useful also. – maldata Sep 11 '19 at 16:44