我写了一个简单的代码来使用分隔符在 C 中拆分字符串。当我删除所有释放项时,代码运行良好但会导致内存泄漏。当我不删除 free 时,它不会显示内存泄漏但会出现段错误。什么是 wring 以及如何解决它?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
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;
}
最佳答案
变量 sizeNames
是一个指针数组,而不是需要以空字符结尾的字符串(字符数组)。
所以删除这个:
*(sizeNames + idx) = 0;
然后改变这个:
for (i=0; *(sizeNames+i); i++)
对此:
for (i=0; i<size; i++)
关于c - 在 C 中使用定界符拆分字符串 - 段错误,无效自由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23277830/