C中带分隔符的拆分字符串-分段错误,无效
我编写了一个简单的代码,用分隔符拆分C中的字符串。当我删除所有空闲时,代码工作得很好,但会导致内存泄漏。当我不删除空闲时,它不会显示内存泄漏,但会给出分段错误。。什么是wring以及如何解决它C中带分隔符的拆分字符串-分段错误,无效,c,string,segmentation-fault,invalidation,C,String,Segmentation Fault,Invalidation,我编写了一个简单的代码,用分隔符拆分C中的字符串。当我删除所有空闲时,代码工作得很好,但会导致内存泄漏。当我不删除空闲时,它不会显示内存泄漏,但会给出分段错误。。什么是wring以及如何解决它 #include <stdio.h> #include <stdlib.h> #include <string.h> unsigned int countWords(char *stringLine) { unsigned int count = 0;
#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;
}
#包括
#包括
#包括
无符号整数countWords(字符*stringLine)
{
无符号整数计数=0;
char*tmp=弦线;
char*last=0;
常量char delim='/';
而(*tmp)
{
如果(delim==*tmp)
{
计数++;
last=tmp;
}
tmp++;
}
返回计数;
}
char**getWordsFromString(char*stringLine)
{
字符**sizeNames=0;
无符号整数计数=0;
常量字符*delim=“/”;
count=countWords(stringLine);
sizeNames=malloc(sizeof(char*)*count);
if(sizeNames==NULL)
{
返回NULL;
}
if(sizeNames)
{
大小\u t idx=0;
char*token=strtok(stringLine,delim);
while(令牌)
{
如果(idx>计数)
{
出口(-1);
}
*(sizeNames+idx++)=strdup(令牌);
token=strtok(0,delim);
}
如果(idx==计数-1)
{
出口(-1);
}
*(sizeNames+idx)=0;
}
返回sizeNames;
}
无效显示字(字符*字符串线)
{
无符号int size=countWords(stringLine),i=0;
char**sizeNames=getWordsFromString(字符串线);
对于(i=0;*(sizeNames+i);i++)
{
printf(“word=[%s]\n”,*(sizeNames+i));
免费(*(sizeNames+i));
}
printf(“\n”);
免费(sizeNames);
}
int main()
{
char words[]=“hello/world/!/its/me/”;
showWords(单词);
返回0;
}
在getWordsFromString中
*(sizeNames + idx) = 0;
在分配的内存结束后写入一个,当您尝试释放它时,会出现SEGFULT。在malloc中尝试计数+1:
sizeNames = malloc(sizeof(char*) * (count+1) );
变量
sizeNames
是指针数组,而不是需要以空字符结尾的字符串(字符数组)
因此,请删除以下内容:
*(sizeNames + idx) = 0;
改变这一点:
for (i=0; *(sizeNames+i); i++)
为此:
for (i=0; i<size; i++)
(i=0;i)的