0

I have the following code to split strings by tokens:

char **strToWordArray(char *str, const char *delimiter)
{
  char **words;
  int nwords = 1;
  words = malloc(sizeof(*words) * (nwords + 1));

  int w = 0;
  int len = strlen(delimiter);
  words[w++] = str;
  while (*str)
  {
    if (strncmp(str, delimiter, len) == 0)
    {
      for (int i = 0; i < len; i++)
      {
        *(str++) = 0;
      }
      if (*str != 0) {
        nwords++;
        char **tmp = realloc(words, sizeof(*words) * (nwords + 1));
        words = tmp;
        words[w++] = str;
      } else {
          str--;
      }
    }
    str++;
  }
  words[w] = NULL;
  return words;
}

If I do this:

char str[] = "abc/def/foo/bar";
char **words=strToWordArray(str,"/"); 

then the program works just fine but if I do this:

char *str = "abc/def/foo/bar";
char **words=strToWordArray(str,"/");

then I get a segmentation fault.

Why is that? The program expects a char* as an argument then why does a char* argument crash the program?

Barmar
  • 741,623
  • 53
  • 500
  • 612
buddy2891
  • 157
  • 10
  • TL;DR: Your modifying `str`, but when you do `char* str = ""` you can't modify that data because what you have is a pointer to memory you aren't allowed to touch. `char[] str = ""` is a copy you can do whatever you want to. – Chad Aug 24 '17 at 02:51

1 Answers1

1

Because the function contains:

    *(str++) = 0;

which modifies the string that was passed to it. When you do:

char *str = "abc/def/foo/bar";

str points to a read-only string literal. See the section titled Attempting to modify a string literal in this question:

Definitive List of Common Reasons for Segmentation Faults

Barmar
  • 741,623
  • 53
  • 500
  • 612