2012-04-17 56 views
1

我會問你一些真正簡單的實現搜索計劃算法的程序的幫助。那麼,我得到的問題對我來說有點奇怪:在爲函數中的本地聲明的簡單字符數組分配內存之後,我在這個數組上工作,它具有所有期望的行爲並且一切正常,但是當我調用在函數結束之前,向該數組釋放()函數,程序停止並中止。如果有人遇到這個問題(或者不是)可以幫助我,我會非常感激。那麼,這裏遵循的「模擬」幾行代碼來展示一下我說的(它不正是上寫的,但:釋放先前分配的內存後程序中止

char* v_AllTheWorld 
char* v_ReadALineOfTheWorld; 

v_AllTheWorld = malloc(COLUMNS * LINES * sizeof(char)); /*LINES and COLUMNS are defined constants*/ 

if(v_AllTheWorld == NULL) 
{ 
    fprintf(stderr, "..."); //etc, etc. 
    exit(1); 
} 

v_ReadALineOfTheWorld = malloc(COLUMNS * sizeof(char)); /*the "sizeof(char)" looks useless, but there's no point in talking about that here, i guess.*/ 

if(v_ReadALineOfTheWorld == NULL) 
{ 
    fprintf(stderr, "..."); //etc, etc. 
    exit(1); 
} 

while(/*some_condition (number of lines to be read)*/) 
{ 
    //read data string from stream and stores in v_ReadALineOfTheWorld (fscanf); 
    //appends the read data to v_AllTheWorld (strncat); 
} 

free(v_ReadALineOfTheWorld); 
/*The program is stopping right after this call in the debug.*/ 

return v_AllTheWorld; 

我沒有把函數的頭部,報關,並且我沒有表示數據流或數據如何被詳細處理,但是沒有其他的「malloc」或「free」調用被創建,並且所有寫入的代碼都被無條件地執行(超出了「if 「或類似的)當然,最後一個行爲不包括配置測試,但你得到了我說的。

所以,我希望我這樣做是正確的要求這種方式,我希望我詳細問題是正確的,希望你能幫助我。

哦,我差點忘了:你可能已經注意到,該方案是C.

+0

我們可以看到while循環的內容嗎?我懷疑你正在增加'v_ReadALineOfTheWorld'指針,其中'free(v_ReadALineOfTheWorld)'會導致未定義的行爲。請注意,您釋放的指針應與從malloc返回的指針相同。 – Naveen 2012-04-17 05:01:27

+1

您是否嘗試使用GDB並查看內存位置? – noMAD 2012-04-17 05:01:53

+0

另外,嘗試'calloc(v_ReadALineOfTheWorld,0)' – noMAD 2012-04-17 05:04:56

回答

3

如果你正在寫的v_ReadALineOfTheWorld邊界之外就會出現這種情況。一些malloc圖書館存儲有關區域周圍的malloc d區域的信息,並且如果您損壞該信息free可能會崩潰。

+0

好吧,我會盡力檢查它。謝謝。 – user1337778 2012-04-17 05:16:55