在C中拆分带分隔符的字符串 – 分段错误,无效空闲

我写了一个简单的代码来在C中用分隔符分割字符串。 当我删除所有自由时,代码工作得很好,但会导致内存泄漏。 当我不删除自由时,它不会显示内存泄漏但会给出分段错误。什么是拧干以及如何解决?

#include  #include  #include  unsigned int countWords(char *stringLine) { unsigned int count = 0; char* tmp = stringLine; char* last = 0; const char delim = '/'; while (*tmp) { if (delim == *tmp) { count++; last = tmp; } tmp++; } return count; } char **getWordsFromString(char *stringLine) { char** sizeNames = 0; unsigned int count = 0; const char *delim = "/"; count = countWords(stringLine); sizeNames = malloc(sizeof(char*) * count); if(sizeNames == NULL) { return NULL; } if (sizeNames) { size_t idx = 0; char* token = strtok(stringLine, delim); while (token) { if(idx > count) { exit(-1); } *(sizeNames + idx++) = strdup(token); token = strtok(0, delim); } if(idx == count - 1) { exit(-1); } *(sizeNames + idx) = 0; } return sizeNames; } void showWords(char *stringLine) { unsigned int size = countWords(stringLine), i = 0; char** sizeNames = getWordsFromString(stringLine); for (i = 0; *(sizeNames + i); i++) { printf("word=[%s]\n", *(sizeNames + i)); free(*(sizeNames + i)); } printf("\n"); free(sizeNames); } int main() { char words[] = "hello/world/!/its/me/"; showWords(words); return 0; } 

Variable sizeNames是一个指针数组,而不是一个需要以null字符终止的字符串(字符数组)。

所以删除这个:

 *(sizeNames + idx) = 0; 

并改变这个:

 for (i=0; *(sizeNames+i); i++) 

对此:

 for (i=0; i 

在getWordsFromString中,

  *(sizeNames + idx) = 0; 

在分配的内存结束后写入一个,当您尝试释放它时,会出现段错误。 在malloc中尝试count + 1:

 sizeNames = malloc(sizeof(char*) * (count+1) );