【发布时间】:2020-09-22 11:24:51
【问题描述】:
您好,我正在删除代码中的内存泄漏,但我卡住了。
这里有函数:
char* MakeLowerCase(char* word)
{
char* lower = (char *)malloc(sizeof(char)*strlen(word)+1);
strcpy(lower, word);
int i = 0;
for(i = 0; i < strlen(lower); i++){
lower[i] = tolower(lower[i]);
}
return lower;
}
void sortedInsert(Word** pH, Word* new_node)
{
Word* current;
/* Special case for the head end */
if (*pH == NULL || strcmp(MakeLowerCase((*pH)->word), MakeLowerCase(new_node->word)) == 1)
{
new_node->pNext = *pH;
*pH = new_node;
}
else
{
/* Locate the node before the point of insertion */
current = *pH;
while (current->pNext!=NULL &&
strcmp(MakeLowerCase(current->pNext->word), MakeLowerCase(new_node->word)) == -1)
{
current = current->pNext;
}
new_node->pNext = current->pNext;
current->pNext = new_node;
}
}
使用这些功能后,我的整个列表都已排序。但是为了避免 MakeLowerCase 的内存泄漏,我尝试了这样的事情:
void sortedInsert(Word** pH, Word* new_node)
{
Word* current;
/* Special case for the head end */
if(*pH = NULL)
{
*pH = new_node;
return ;
}
char* word1 = MakeLowerCase((*pH)->word);
char* word2 = MakeLowerCase(new_node->word);
if (*pH == NULL || strcmp(word1, word2) == 1)
{
new_node->pNext = *pH;
*pH = new_node;
}
else
{
/* Locate the node before the point of insertion */
current = *pH;
char* word3 = MakeLowerCase(current->pNext->word);
char* word4 = MakeLowerCase(new_node->word);
while (current->pNext!=NULL && strcmp(word3, word4) == -1)
{
current = current->pNext;
}
new_node->pNext = current->pNext;
current->pNext = new_node;
}
free(word1);
free(word2);
}
更改后,我的列表没有像之前那样排序(只是其中一部分以奇怪的方式排序)。我做错了什么?
【问题讨论】:
-
Ofc after current->pNext 我对 word3 和 word4 使用 free()
-
只需使用 stricmp() 进行比较。
-
我不能只使用 strcmp() 因为我需要比较小写字母。
-
我怕你把小写字母 i 看多了:str - i - cmp i=ignorecase
-
嗯,是的。你说得对。我会检查那个解决方案
标签: c list sorting memory struct