2012-06-27 60 views
0

爲了在malloc命令之後釋放內存以防止內存泄漏,我在運行時遇到了堆損壞問題。我的調試告訴我,我的應用程序在堆緩衝區到達後試圖寫入內存。以下是我已簡化以隔離我的問題。在釋放C中分配的內存時發生堆損壞

#include <stdio.h> 
#include <stdlib.h> 
#include <math.h> 

main(){ 

int i,j,n; 
int temp[4]; 
int **a; 

printf("Amount of intervals to be entered: "); 
scanf("%d", &n); 

//allocate memory for a 2d array of size (n x 4) 
a = (int**) malloc(n*sizeof(int*)); 
for (i=0;i<4;i++){ 
    a[i] = (int*) malloc(4*sizeof(int)); 
} 

if (!a){ 
    printf("malloc failed %d\n",__LINE__); 
    exit(0); 
} 

printf("Please enter the intervals a line at a time followed by a return: \n"); 
for(i=0;i<n;i++){ 
    scanf("%d %d %d %d",&a[i][0], &a[i][1], &a[i][2], &a[i][3]); 
} 

for(i=0;i<n;i++){ 

    printf("%d, %d, %d, %d\n", a[i][0], a[i][1], a[i][2], a[i][3]); 

} 


// free up the allocated memory 


for (i=0;i<n;i++){ 
    free(a[i]); 
} 

free(a); 




} 

我對分配和取消分配內存不是很熟悉,所以我對我應該做什麼感到不知所措。

+0

釋放內存通常是一個好主意,但在此也值得注意的是,當程序退出時,所有內存都會被隱式釋放。 (所以你在技術上不需要在這種情況下免費任何東西。) – duskwuff

回答

3

可能還有其他問題。但是,這至少是錯誤的:

a = (int**) malloc(n*sizeof(int*)); 
for (i=0;i<4;i++){     <---- 4 should be n 
    a[i] = (int*) malloc(4*sizeof(int)); 
} 
+1

打我55秒:-) –

+0

非常感謝很多,我討厭它,當它容易因爲我覺得愚蠢,但我也很高興同時:)謝謝! –

0
//allocate memory for a 2d array of size (n x 4) 
a = (int**) malloc(n*sizeof(int*)); 

if (!a){ 
    printf("malloc failed %d\n",__LINE__); 
    exit(0); 
} 

for (i=0;i<n;i++){ 
    a[i] = (int*) malloc(4*sizeof(int)); 
} 

-move電話後malloc的檢查,利用 「一」

- 使用之前的 「n」

- 刪除「的數學「h」「temp」和「j」