Search code examples
cstringpointersstrsep

String token from `strsep` not printing (seg fault)


I'm using with a smaller piece of code to test functionality for a larger (beginner) program, but I have a problem displaying the token I've pulled out of a string.

I found and used:

#include <stdio.h>
#include <string.h>

int main()
{

char *string, *found;

string = strdup ("1/2/3");
printf("Original string: '%s'\n",string);

while ((found = strsep(&string,"/")) != NULL )
  printf ("%s\n",found);

return (0);
}

and this works fine, prints the tokens one at a time as strings.

Then when I try and move to a user entered string:

#include <stdio.h>
#include <string.h>

int main()
{
  char string[13];
  char *found, *cp = string;

  fprintf(stderr, "\nEnter string: ");
  scanf("%12s",string);
  printf("Original string: '%s'\n",string);

  while((found =  strsep(&cp,"/,-")) != NULL )
    printf("Test 1"); /*To pinpoint where the seg fault arises*/
    printf("%s\n",found);

  return(0);
}

I get a seg fault on the printf("%s\n",found); line. I'm getting the hang of basics of pointers, arrays and strings, but clearly I'm missing something, and would love for someone to tell me what it is!

Also - if I change the argument of printf("%s\n",found); e.g. to printf("%i\n",found); I get some randomness returned, but always the correct amount, e.g. If I enter 1/2/3 I get three lines of junk, entering 1111/2222 gives two lines. I tried %c, %i, %d, %p and they all do the same, but %s seg faults.

I'm completely stumped.


Solution

  • The segfault is because you're missing braces around your while. You'll keep printing "Test 1" until strsep returns NULL, then you try to print that result (and segfault).

    With several warning flags (probably -Wall), gcc helps out here:

    sep.c:13:3: warning: this ‘while’ clause does not guard... [-Wmisleading-indentation]
       while((found =  strsep(&cp,"/,-")) != NULL )
       ^~~~~
    sep.c:15:5: note: ...this statement, but the latter is misleadingly indented as if it is guarded by the ‘while’
         printf("%s\n",found);
         ^~~~~~
    

    With braces added around the while, the program works as expected:

    ./sep 
    
    Enter string: abc/def
    Original string: 'abc/def'
    Test 1abc
    Test 1def