我寫了一個簡單的代碼在C與分隔符拆分字符串。當我刪除所有的自由空間時,代碼很好,但是會導致內存泄漏。當我不刪除免費,它不顯示內存泄漏,但給分段錯誤..什麼是絞線和如何解決它?分割字符串在C分隔符 - 分段錯誤,無效免費
#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;
}