2014-02-27 42 views
0

您好我正在學習一些調試概念。在這個程序中,我試圖模擬核心轉儲。我預計核心將被傾倒但它不會生成核心。程序執行沒有任何問題。後免費指針記憶,我可以重新分配價值

首先,我分配用於PTR 20個字節。我將一個新字符串複製到ptr。然後我免費ptr然後打印ptr它沒有任何pblm工作。最後我重新分配一些其他字符串,我期望這次它可能會生成核心轉儲。但我沒有得到任何核心轉儲。任何人都可以解釋爲什麼它沒有生成核心轉儲。

int main() 
{ 
    char *ptr; 
    ptr =(char*) malloc (20); 
    strcpy(ptr,"MemoryOperations"); 
    printf("Before Free memory : %s\n",ptr); 
    free(ptr); 
    printf("After Free memory : %s\n",ptr); 
    strcpy(ptr,"MemReassign"); 
    printf("After Re Assigning : %s\n",ptr); 
    return 0; 
} 

相同的代碼我用dbx中運行,

(dbx) check -all 
access checking - ON 
memuse checking - ON 
(dbx) run 
Running: a.out 
(process id 19081) 
RTC: Enabling Error Checking... 
RTC: Running program... 
Before Free memory : MemoryOperations 
Read from unallocated (rua): 
Attempting to read 1 byte at address 0x100101a48 
which is 2232 bytes into the heap; no blocks allocated 
stopped in _ndoprnt at 0xffffffff671abbf0 
0xffffffff671abbf0: _ndoprnt+0x1c04: call  _PROCEDURE_LINKAGE_TABLE_+0x620 [PLT] ! 0xffffffff67340d20 
(dbx) exit 
+1

如果你想有一個核心轉儲,叫'中止()'。 –

+0

那件事和我查過的所有東西,但我不知道它不會導致問題的原因。 – Jeyamaran

+1

編寫C時不要施加'malloc'的返回值。 –

回答

1

free(ptr)不會修改ptr的值。它標誌着相應的位置可用於重新分配。

A block of memory previously allocated by a call to malloc, calloc or realloc is 
deallocated, making it available again for further allocations. 
Notice that this function does not change the value of ptr itself, 
hence it still points to the same (now invalid) location. 
--cplusplus.com 

因此,如果你真的想生成核心轉儲嘗試一些確保拍攝然後嘗試瘋狂的東西,如:

char d=10/0; //arithematic 

char *a=malloc(1); 
free(a); 
a=NULL; //this is important after free. 
*a=100; 
+0

我不是想模擬核心轉儲。我只是想知道它不傾銷核心的原因。 – Jeyamaran

+1

井的原因(如我上面所解釋的),你釋放的指針仍然指向相同的內存地址(在進程堆,因此目前的進程訪問),即使經過。當你釋放內部標記可用於重新分配的相應內存位置時。這與使用未初始化的指針不同,因爲它可以指向內存中的任何位置(甚至指向不可訪問的位置) – Suryavanshi

3

如果寫入內存已經釋放後,任何事情都有可能發生。這是未定義的行爲。你可以得到一個核心轉儲或不。在你的情況下,你不會得到核心轉儲,因爲內存,即使它已經被釋放,仍然可以被你的進程訪問。 BUF,如果你會做另一malloc只是return 0語句之前和寫入內存,字符串「重新勘定後...」將最有可能被改寫。

使用dbx時,printf("After Free memory : %s\n",ptr);語句會產生「未分配讀取」錯誤,因爲您已打開訪問檢查,但沒有dbx根本沒有訪問檢查。

用於模擬核心轉儲,你可以這樣做:

void main() 
{ 
    char *p = NULL ; 
    *p = 'A' ; 
} 

這會崩潰在大多數平臺。