我有一小段代碼。我編譯它與-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;
}
此外,請考慮http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858。 – unwind