2011-07-04 58 views
5

我有一小段代碼。我編譯它與-lmcheck因爲我試圖調試代碼,我有類似的錯誤。內存調整錯誤

memory clobbered before allocated block 

有人能解釋爲什麼free(ptr)將拋出我這個錯誤的原因:

當我運行這段代碼我得到這個錯誤?

我還能如何釋放指針?

謝謝。

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 
#include <unistd.h> 
#define LEN 5 


int main(int argc, char *argv[]){ 

    char *ptr = NULL; 

    ptr = (char *) malloc(LEN+1);// +1 for string 
    strcpy(ptr, "hello"); 

    int i = 0; 
    for(i = 0; i<LEN; i++) 
    { 
     printf("ptr[%d] = %c\n", i, ptr[i]); 
     ptr++; 
    } 
    free(ptr); 


    return 0; 
} 
+0

此外,請考慮http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858。 – unwind

回答

8

您正在遞增ptr,因此更改它指向的地址。你不能那樣做。

在你的情況,有一個單獨的指針,讓我們說char * p = ptrp離開ptr不變,以便您可以free(ptr)後做您的操作。

編輯再次看看你的代碼,我發現你不應該在做ptr++。您正在訪問像ptr[i]這樣的數組中的字符,如果您弄亂ptr指針,則您正在更改基址,並且使用ptr[i]訪問字符可能會導致(並導致)意外的結果。

如果你只是刪除該行(ptr++),你的代碼將神奇地工作。 如果你想探索指針的概念,並嘗試另一種解決方案,你的代碼可能是這個樣子:

int main(int argc, char *argv[]){ 

    char *ptr = NULL; 
    char * p; 

    ptr = (char *) malloc(LEN+1);// +1 for string (please check for NULL) 
    p = ptr; 

    strcpy(ptr, "hello"); 

    int i = 0; 
    while (*p) // note how I changed it to a while loop, C strings are NULL terminated, so this will break once we get to the end of the string. What we gain is that this will work for ANY string size. 
    { 
     printf("ptr[%d] = %c\n", i++, *p); // here i dereference the pointer, accessing its individual char 
     p++; 
    } 
    free(ptr); 


    return 0; 
} 
+1

優秀的解釋!謝謝你的加倍努力。 –

2

因爲ptr不再指向你分配的內存的基礎。

1

此外,在您增加ptr後,表達式ptr[i]不會返回您所期望的;這就是爲什麼輸出以「hlo」開頭的原因。

1

在評論中找到答案。 當你分配一些內存時,通常情況下,內存管理框架會通過向分配的內存區域添加更多信息(可以稱爲頁眉和頁腳)來跟蹤它。當釋放該內存時,會匹配相同的信息以檢測任何不需要/無效的內存訪問。

int main(int argc, char *argv[]){ 

    char *ptr = NULL; 
    char* temp = NULL;   // Have a temp pointer. 

    ptr = (char *) malloc(LEN+1);// +1 for string 
    strcpy(ptr, "hello"); 

    temp = ptr;     // manipulate temp pointer instead of ptr itself 

    int i = 0; 
    for(i = 0; i<LEN; i++) 
    { 
     printf("ptr[%d] = %c\n", i, temp[i]); 
     temp++;     // Why you are incrementing this? Just to print, there is no need of this. 
    } 
    free(ptr); 


    return 0; 
}