我一直在運行mallocing /釋放內存一個奇怪的問題。我不能顯示整個代碼本身,所以請做一個非常裸露的部分:malloc問題和內存堆
#include <stdio.h>
int main(void)
{
void *ptr;
ptr = malloc(sizeof(node));
/* making sure what the value is when it was initialized */
printf("head_node: %p\n", ptr);
/* i do a lot of things here, such as appending the node, sometimes truncating them */
/* --------------------------------------------------------------------------------*/
/* making sure what the value is still the same: */
printf("head_node: %p\n", ptr);
free(ptr);
printf("done");
}
其中節點聲明在其他地方。
在我釋放ptr的地方,它的初始值是相同的權利釋放它之前,它不是NULL,我得到在Windows中的錯誤對話框。
現在這裏是奇怪的部分。當我在MinGW下編譯它並在MSYS(MinGW控制檯shell)或其外部運行它時,它不會遇到任何錯誤。當我在MS Visual Express 2012下構建它並在它下面進行調試時,它不會遇到任何錯誤。但是當我運行由MS Visual Visual Studio構建的同一個程序時,我總是得到一個錯誤。
什麼是更奇怪的是,它首先打印出「完成」,這是在錯誤彈出之前程序的最後點。當跟蹤錯誤的來源時不是很有用...
如果在正常的Windows環境中有任何錯誤被捕獲,那爲什麼不在MS Visual?中?
這裏所顯示的異常消息:
File: f:\dd\vctools\crt_bld\self_x86\crt\src\dbgheap.c
Line: 1322
Expression: _CrtIsValidHeapPointer(pUserData)
這似乎是一個可編譯的最小代碼。 *此*代碼是否顯示問題行爲?如果它確實表明你的環境存在問題,如果不是,那麼你可以開始在「很多事情」的一小部分中重新加入以學習更多東西。這就是說,我懷疑你是雙免費的。請注意'free'不會改變它的參數值。 – dmckee
不幸的是,這個最小的代碼不會重現錯誤。實際的主代碼很長很複雜。它不得不包括其他文件,我不願意這樣做。當你說我可能會雙倍釋放某些東西時,你可能會做些什麼。我會檢查它。 –