问题描述
试图了解回答我的问题。
Trying to understand answers to my question
http://stackoverflow.com/questions/2336345/what-happens-when-tried-to-free-memory-allocated-by-heap-manager-which-allocates
我写了这个功能,并通过其输出困惑
I wrote this function and puzzled by its output
int main(int argc,char **argv){
char *p,*q;
p=malloc(1);
strcpy(p,"01234556789abcdefghijklmnopqrstuvwxyz"); //since malloc allocates atleast 1 byte
q=malloc(2);
// free(q);
printf("q=%s\n",q);
printf("p=%s\n",p);
return 0;
}
输出
q=vwxyz
p=01234556789abcdefghijklm!
任何一个可以解释这种现象?或者这是实现特定的?
Can any one explain this behavior? or is this implementation specific?
此外,如果免费(Q)是注释掉,我得到SIGABRT。
also if free(q) is uncommented, I am getting SIGABRT.
推荐答案
您需要复制多个字节 * P
比您已经分配,覆盖任何可能已经在分配的空间之后的存储单元。
You are copying more bytes to *p
than you have allocated, overwriting whatever might have been at the memory locations after the allocated space.
当你再调用的malloc
再次,它需要记忆的一部分,它知道是在时刻(这恰好是几个字节后<$ C $未使用C> * p 这个时候),也写入一些记录信息,并返回一个新的指针到该位置。
When you then call malloc
again, it takes a part of memory it knows to be unused at the moment (which happens to be a few bytes after *p
this time), writes some bookkeeping information there and returns a new pointer to that location.
簿记信息的malloc
写恰好开始使用'!在此运行,随后是零字节,所以你的第一个字符串被截断。新指针发生点之前已改写了内存的结束。
The bookkeeping information malloc
writes happens to start with a '!' in this run, followed by a zero byte, so your first string is truncated. The new pointer happens point to the end of the memory you overwrote before.
这是所有具体实施,可能导致不同的结果每次运行或者根据月亮的圆缺。第二次调用的malloc()
也绝对会在其刚刚崩溃的可怕方式程序(特别是因为你可能会被改写存储正确的的malloc
内部使用)。
All this is implementation specific and might lead to different results each run or depending on the phase of the moon. The second call to malloc()
would also absolutely be in its right to just crash the program in horrible ways (especially since you might be overwriting memory that malloc
uses internally).
这篇关于的malloc怪异的行为()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!