这是我第一次使用动态内存分配,我不知道如何检查代码中的内存泄漏
一般情况下,我如何检查visual中的内存泄漏?我不知道如何跟踪堆和堆,所以我主要是在黑暗中射击。
我应该提一下,我使用了windows 10,据我所知,华润不支持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;
}发布于 2021-12-22 11:54:10
要检查内存泄漏,可以使用像这样的工具--尽管这些工具不能保证内存泄漏的存在或查找内存泄漏的任何位置--可能存在错误的阳性和否定--它们的结果仍然为您再次检查代码提供了非常有价值的提示。
监视内存消耗也可以为您提供进一步的提示;如果超出合理的范围,则可能会出现内存泄漏。
对于你的具体例子:
第一个变体可能会产生内存泄漏,但不一定会导致内存泄漏。
Dictionary d1 = ...;
Dictionary d2 = createDic(d1, &n);
// now you could use both of d1 and d2
// however risk of double deletion if re-allocation failed;
// need to compare d1 and d2 for equality before freeing them
Dictionary d3 = ...; // assume this is the sole pointer to d3
d3 = createDic(d3, &n); // if re-allocation succeeded last reference to
// old dictionary is lost -> memory leak第二个变体避免了这一点,但也有另一个缺点:
Dictionary d1 = ...;
Dictionary d2 = createDic(d1, &n);如果成功,指针d1将失效,读取它会导致未定义的行为。因此,您也必须将其更新为新值。
总之,第二个变式应该会带来较少的麻烦,所以我更喜欢它。顺便说一句:如果你修改第一个变体,在返回之前删除旧字典,那就相当于第一个变体,以防成功……
https://stackoverflow.com/questions/70448444
复制相似问题