内存错误重挫 [英] Memory Clobbering Error
问题描述
我有一小块code的。我与 -lmcheck
编译它,因为我尝试调试code,其中我也有同样类似的错误。
当我运行这个code我得到这个错误:
内存分配惨败前挡
有人能解释为什么免费(PTR)
将抛出我这个错误?
怎么我还能释放指针?
感谢。
的#include<&stdio.h中GT;
#包括LT&;&string.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&unistd.h中GT;
的#define LEN 5
INT主(INT ARGC,CHAR *的argv []){ 字符* PTR = NULL; PTR =(字符*)malloc的(LEN + 1); // +1字符串
的strcpy(PTR,你好); INT I = 0;
对于(i = 0; I< LEN,我++)
{
的printf(PTR [%d个=%C \\ N,我,PTR [I]);
PTR ++;
}
免费(PTR);
返回0;
}
正在递增 PTR
,因此改变它指向的地址。你不能做到这一点。
在你的情况,有一个单独的指针,假设的char * p = PTR
和 P
离开 PTR
不变,以便您可以免费(PTR)
之后。
修改以你的code第二次看,我发现你正在做 PTR ++
时,你不应该。您正在访问像 PTR数组中的字符[I]
,如果乱用 PTR
的指针,你是改变基址和 PTR访问字符[I]
可能会导致(并会导致)意外的结果。
如果你只是删除了这一行( PTR ++
)的code会奇迹般地工作。
如果你想探索指针的概念,尝试另一种解决方案,您的code可能是这个样子:
INT主(INT ARGC,CHAR *的argv []){ 字符* PTR = NULL;
字符* P; PTR =(字符*)malloc的(LEN + 1); // +1字符串(请检查NULL)
P = PTR; 的strcpy(PTR,你好); INT I = 0;
而(* P)//注意我是如何变成一个while循环,C字符串是NULL终止,所以这将打破,一旦我们得到的字符串的结尾。我们得到的是,这适用于任何字符串大小工作。
{
的printf(PTR [%d个=%C \\ N,我++,* P); //这里我解引用指针,访问其个人CHAR
p ++;
}
免费(PTR);
返回0;
}
I have a small piece of code. I compiled it with -lmcheck
as I am trying to debug a code where I have the same similar error.
I get this error when I run this code:
memory clobbered before allocated block
Can someone explain the reason why free(ptr)
will throw me this error?
How else can I free the pointer?
Thanks.
#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;
}
You are incrementing ptr
, therefore changing the address that it points to. You can't do that.
In your case, have a separate pointer, let's say char * p = ptr
and do your operations with p
leaving ptr
intact so you can free(ptr)
later.
EDIT Taking a second look at your code, I found that you are doing ptr++
when you shouldn't. You are accessing the characters in the array like ptr[i]
, if you mess with the ptr
pointer, you are changing the base address and accessing the characters with ptr[i]
can lead (and will lead) to unexpected results.
If you simply remove that line (ptr++
) your code will magically work.
If you want to explore the pointer concept and try another solution, your code could look something like this:
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;
}
这篇关于内存错误重挫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!