【发布时间】:2011-07-04 12:25:28
【问题描述】:
我有一小段代码。我使用-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;
}
【问题讨论】:
标签: c memory-leaks malloc