【发布时间】:2022-01-23 15:24:32
【问题描述】:
这是我第一次使用动态内存分配,我不知道如何检查我的代码中的内存泄漏
一般来说,我如何检查 Visual Studio 中的内存泄漏?我不知道如何跟踪堆和堆栈,所以我主要是在黑暗中拍摄。
我应该提到我使用的是 Windows 10,据我所知 Valgrind 不提供对 W10 的支持
Dictionary* createDic(Dictionary* dics, int* size) {
Dictionary* temp = NULL;
//some extra code for the variables below which arent al that important for the question
temp = malloc(++*size * sizeof(Dictionary));
if (temp==NULL)
{
printf("\nThe creation of the dictionary has failed!");
*size+=-1;
freeArray(splitReciever,count);
return dics;
}
for (int i = 0; i < (*size - 1); i++)
{
temp[i] = dics[i];
}
temp[*size - 1].languages = splitReciever;
temp[*size - 1].numOfLanguages = count;
temp[*size - 1].wordList = NULL;
dics = temp;
return dics;
}
我还想知道这段代码是否可以再次工作而不会导致内存泄漏?
Dictionary* createDic(Dictionary* dics, int* size) {
Dictionary* temp = NULL;
//some extra code for the variables below which arent al that important for the question
temp = realloc(dics , ++*size * sizeof(Dictionary));
if (temp==NULL)
{
printf("\nThe creation of the dictionary has failed!");
*size+=-1;
freeArray(splitReciever,count);
return dics;
}
temp[*size - 1].languages = splitReciever;
temp[*size - 1].numOfLanguages = count;
temp[*size - 1].wordList = NULL;
dics = temp;
return dics;
}
【问题讨论】:
-
你试过 Valgrind 吗?
-
首先不要做“聪明”的事情,比如将
++表达式与其他代码混合。
标签: c memory-leaks malloc dynamic-memory-allocation realloc