传递char *作为参数会破坏程序,而char []则不会

时间:2017-08-24 02:45:36

标签: c pointers char

我有以下代码用标记来分割字符串:

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;
}

如果我这样做:

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

那么程序运行得很好但是如果我这样做:

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

然后我得到了一个分段错误。

为什么?程序期望char*作为参数然后为什么char*参数会使程序崩溃?

1 个答案:

答案 0 :(得分:1)

因为该功能包含:

    *(str++) = 0;

修改传递给它的字符串。当你这样做时:

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

str指向只读字符串文字。请参阅此问题中标题为尝试修改字符串文字的部分:

Definitive List of Common Reasons for Segmentation Faults