guckmalmensch
guckmalmensch

Reputation: 1181

strsep() with char pointer gives segmentation fault in c

int main() {
  char* instruction = "x10,   14(x2)";
  char* rd = strsep(&instruction, ",");
  printf("%c", *rd);
    
  return(0);
}

I was trying to run this few lines, and i was expecting it to print "x", but it gives segmentation fault. What did i do wrong?

Upvotes: 2

Views: 398

Answers (1)

kiran Biradar
kiran Biradar

Reputation: 12732

From strsep man

 char *strsep(char **stringp, const char *delim);

 If *stringp is NULL, the strsep() function returns NULL and does
   nothing else.  Otherwise, this function finds the first token in the
   string *stringp, that is delimited by one of the bytes in the string
   delim.  This token is terminated by overwriting the delimiter with a
   null byte ('\0'), and *stringp is updated to point past the token.
   In case no delimiter was found, the token is taken to be the entire
   string *stringp, and *stringp is made NULL.

You are trying to modify the ready only string by passing it to strsep.

  char* instruction = "x10,   14(x2)";
  char* rd = strsep(&instruction, ",");

try

  char* instruction = "x10,   14(x2)";
  char *temp = strdup(instruction);
  char *save = temp;
  char* rd = strsep(&temp, ",");
  free(save);

You need to preserve a copy of the pointer to temp so it can be freed later.

Example: From the description "stringp is updated to point past the token.", if you use free(temp) you will pass an invalid address to free() because temp no longer points to the beginning of the allocated block it points somewhere in the interior of it.

Upvotes: 3

Related Questions