2011-10-26 91 views
3

我想使用free()從內存中刪除整個矩陣數組。我該怎麼做?free()C中的2D數組使用malloc

分配數組:

// test.h 
#include <stdio.h> 
#include <stdlib.h> 
#include <malloc.h> 

#define BYTE unsigned char 
#define my_array(n_height, n_width) (BYTE **)create_array(sizeof(BYTE), (n_height), (n_width)) 

char **create_array(int u_size, int height, int width); 
char **create_array(int u_size, int height, int width) 
{ 
    char **array; 
    int  i; 

    if (!(array=(char **)malloc(height*sizeof(char *)))) { 
     printf("Memory allocation error.\n"); 
     exit(0); 
    } 
    if (!(array[0]=(char *)malloc(height*width*u_size))) { 
     printf("Memory allocation error.\n"); 
     exit(0); 
    } 
    for (i=1; i<height; i++) 
     array[i] = array[i-1] + width*u_size; 
    return array; 
} 

// test.c 
#include "array.h" 
int main() 
{ 
    unsigned char *bytes; 
    BYTE **matrix; 
    matrix = my_array(height, width); 

    int c = 0; 
    for (int h=0; h < height; h++) { 
     for (int w=0; w < (width); w++) { 
      matrix[h][w] = bytes[c]; 
      c++; 
     } 
    } 

    printf("Done.\n"); 

    free(matrix); // really empty memory?? 
} 

我不能肯定是否基質已完全從當我使用免費的(矩陣)的存儲器中移除;

回答

5

對於malloc(),每撥打一次電話,您必須撥打free()。你不能「愚弄」free()免費:幾塊。如果您想只能撥打free()一次,則需要確保將所有必需的內存分配給malloc()

+0

free(matrix [0]); free(matrix); 應該工作還是不工作? – wowofe

+0

@wowofe wowofe:是的。 – caf

+0

@unwind&caf:謝謝! – wowofe

1

如果你喜歡,你可以使用美麗的C99指針到變量長度數組。

分配是這樣的:

char (*arr)[width] = emalloc(width*height); 

指數是這樣的:

arr[23][10] = 2; //row 23, column 10 

而且免費是這樣的:

free(arr); 
+0

什麼是emalloc()? –

+0

@Dave:我會試試你的方法。謝謝! – wowofe

+0

@Alex'emalloc()'是用於'malloc()'的全部使用Plan9的名稱,該名稱返回一個有效指針,或者打印一個錯誤並退出。 – Dave

0

如果要檢查內存被釋放,你應該使用Valgrind程序。
The Valgrind Quick Start Guide

在這種情況下,試試這個:

free(matrix[0]); 
free(matrix); 
+0

這正是我發佈我的問題之前使用的代碼。我不知道,因爲我得到了錯誤 - 免費(矩陣[我]); :test(830,0x7fff73cd4960)對象0x117439a4c的malloc:***錯誤:被釋放的指針未被分配 ***在malloc_error_break中設置斷點來調試 (gdb) – wowofe

+0

這是正確的,您只分配兩次,因此您還必須免費兩次。我建議你使用valgrind程序,這是一個很棒的工具。 – vicentazo

+0

謝謝你的提示!我現在明白了:for(int i = 0; i wowofe

2

你有兩個malloc S,所以你需要兩個free秒。但是如果你重新排列你的分配,你可以優化一點:

/... 
void* mcontent; 
if (!(mcontent = malloc(height*sizeof(char*) + height*width*u_size))) { 
    printf("Memory allocation error.\n"); 
    exit(0); 
} 
array = (char **)mcontent; 
array[0]=(char *)(mcontent + height*sizeof(char*)); 

這有兩個好處。首先,可用性:你只需要釋放你的矩陣「對象」而不會打擾它的製作過程。其次,效率:你有局部性,只有一個分配,這都意味着速度。

+0

謝謝!你的代碼很清楚我如何使用free(),因爲我在循環內掙扎以釋放內存。我現在明白了。 – wowofe

+0

你應該使用'exit(EXIT_FAILURE);'或'exit(1);'not'exit(0);'如果動態內存分配失敗。 – Ultimater