2014-03-25 32 views
0

我遇到了免費的麻煩。我想分配一個* chars的二維數組並釋放它們,但它在運行時失敗。我正在學習指針,可能過於複雜。使用免費()中的問題C

//NUMBEROFLINES, NUMBEROFDIE, and WIDTHOFDIE are some ints (3, 2, 3), 
    int iLineSize, iLine, iDie; 
    char **piDieString; 

    piDieString = (char**)malloc(NUMBEROFLINES * sizeof(*piDieString)); //Allocate number of lines 
    iLineSize = NUMBEROFDIE * WIDTHOFDIE * sizeof(char); //Size of line 
    for(iLine = 0; iLine < NUMBEROFLINES; iLine++) 
    { 
    piDieString[iLine] = (char*)malloc(iLineSize); //Allocate size of lines 
    } 

    //Stuff happens 

    /*Freeing*/ 
    for(iLine = 0; iLine < NUMBEROFLINES; iLine++) 
    { 
    free(piDieString[iLine]); 
    } 
    free(piDieString); 
+2

dont cast malloc –

+0

@nikhilmehta ***不,這是絕對的,可怕的錯誤!***不要給壞的建議。編寫'sizeof(* piDieString)'更好**,因爲它更安全(因爲它消除了冗餘)。 'sizeof'運算符的參數是**未計算的,**因此在'sizeof'內部取消引用未初始化的指針是**有效。** – user3447428

+2

'malloc()''free()'看起來不錯,可能是問題是在'//發生的事情'中。 – Rohan

回答

0

有您打印二維指針的地址如果沒有,那麼試試,你會看到一些令人驚訝的,因爲在redhat我在二維數組在這裏看到動態的地址是不連續否則這個地方我沒有看到任何地方該數組具有非連續的內存。可能是這個不連續造成一些問題。我不是確切的原因。

1

我相信//Stuff happens有問題。

增加了打印出的驗證,如果內存分配得到妥善釋放如下:

#include <stdio.h> 
#define NUMBEROFLINES 3 
#define NUMBEROFDIE 2 
#define WIDTHOFDIE 3 
int main(void) { 

    int iLineSize, iLine, iDie; 
    char **piDieString; 

    piDieString = (char**)malloc(NUMBEROFLINES * sizeof(*piDieString)); //Allocate number of lines 
    printf("Allocated piDieString: 0x%x\n",piDieString); 
    iLineSize = NUMBEROFDIE * WIDTHOFDIE * sizeof(char); //Size of line 

    for(iLine = 0; iLine < NUMBEROFLINES; iLine++) 
    { 
    piDieString[iLine] = (char*)malloc(iLineSize); //Allocate size of lines 
    printf("Allocating piDieString[%d]: 0x%x\n",iLine,piDieString[iLine]); 
    } 

    //Stuff happens 

    /*Freeing*/ 
    for(iLine = 0; iLine < NUMBEROFLINES; iLine++) 
    { 
    printf("Freeing piDieString[%d]: 0x%x\n",iLine,piDieString[iLine]); 
    free(piDieString[iLine]); 
    } 

    printf("\nFreeing piDieString: 0x%x\n",piDieString); 
    free(piDieString); 
    return 0; 
} 

輸出是這樣,這似乎只是罰款。

Allocated piDieString: 0x966e008 
Allocating piDieString[0]: 0x966e018 
Allocating piDieString[1]: 0x966e028 
Allocating piDieString[2]: 0x966e038 
Freeing piDieString[0]: 0x966e018 
Freeing piDieString[1]: 0x966e028 
Freeing piDieString[2]: 0x966e038 

Freeing piDieString: 0x966e008 

"but it fails at runtime"精心...正如你看到一個崩潰?如果是檢查//Stuff happens爲inavlid內存訪問...