[英]how can i check for memory leaks in C?
這是我第一次使用動態 memory 分配,我不知道如何在我的代碼中檢查 memory 泄漏
總的來說,我如何在 Visual Studio 中檢查 memory 泄漏? 我不知道如何跟蹤堆和堆棧,所以我主要是在黑暗中拍攝。
我應該提到我使用了 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;
}
我還想知道這段代碼是否會再次起作用,而不會導致 memory 泄漏?
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;
}
To check for memory leaks tools like valgrind can be used – while these cannot give you guarantees of (in-)existence of memory leaks or for finding any location of a memory leak – there are false positives and negatives possible – their results still provide pretty關於你應該在哪里再次檢查你的代碼的有價值的提示。
監控 memory 的消耗也可以給你進一步的提示; 如果它超出合理限制,那么您可能有 memory 泄漏。
對於您的具體示例:
第一個變體可能會產生 memory 泄漏,但不一定:
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
會失效,讀取它會導致未定義的行為。 因此,您還必須將其更新為新值。
總之,第二個變體應該會帶來更少的麻煩,所以我更喜歡它。 順便說一句:如果您修改該變體以在成功返回之前刪除舊字典,則相當於第一個變體......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.