2

I am working on splitting strings.

When I run this code, I got an error ( Bus error: 10 on MacOs or SegFault on Linux).

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

int main ()
{
  char *str = (char *)malloc(1000*sizeof(char));
  str ="- This, a sample string.";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,.-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  }
  return 0;
}

When I change the str declaration by char str[] ="- This, a sample string."; it works well.

Can anyone tell me why? My brain is melting.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
peletloick
  • 27
  • 5

1 Answers1

2

From the man page of strtok()

Be cautious when using these functions. If you do use them, note that:

  • These functions modify their first argument.

  • These functions cannot be used on constant strings.

As your code, str holds the base address of a statically allocated string literal which is usually read-only.

In your code, change

char *str = (char *)malloc(1000*sizeof(char));
str ="- This, a sample string.";

to

char *str = malloc(1000);
strcpy(str, "- This, a sample string.");

Also, first allocating memory to str using malloc() and then assignning the string literal to str will overwrite the previously allocated memory returned by malloc(), resulting in memory leak.

Next,

char str[] ="- This, a sample string.";

this works well, because here you're initializing a local array and it's containts are modifiable.

Note:

Please do not cast the return value of malloc().

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261