我有以下代码通过标记拆分字符串:
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*
参数会使程序崩溃?
因为该函数包含:
*(str++) = 0;
它修改传递给它的字符串。当您执行以下操作时:
char *str = "abc/def/foo/bar";
str
指向只读字符串文本。请参阅此问题中标题为">尝试修改字符串文本">的部分:
分段错误的常见原因的明确列表