为什么免费的()只设置8个字节第一为零? [英] Why does free() only set the 8 first bytes to zero?

查看:165
本文介绍了为什么免费的()只设置8个字节第一为零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于自由(的)行为问题。

I've a question about free() behavior.

中庸之道一个简单的code这用malloc和strcpy一个char *。因此,所有被设置在堆上:

Juste a simple code which use malloc and strcpy a char*. So, all is set on the HEAP :

(gdb) x/100b 0x602010
0x602010:   66  111 110 106 111 117 114 32
0x602018:   116 111 117 116 32  108 101 32
0x602020:   109 111 110 100 101 0   0   0
0x602028:   0   0   0   0   0   0   0   0
0x602030:   0   0   0   0   0   0   0   0
0x602038:   33  0   0   0   0   0   0   0

当我释放与自由()块,其结果是:

When I free the chunk with free(), the result is :

(gdb) x/100b 0x602010
0x602010:   0   0   0   0   0   0   0   0
0x602018:   116 111 117 116 32  108 101 32
0x602020:   109 111 110 100 101 0   0   0
0x602028:   0   0   0   0   0   0   0   0
0x602030:   0   0   0   0   0   0   0   0
0x602038:   33  0   0   0   0   0   0   0

简单code证明:

Simple code to prove that :

int main ()
{
    const char * str = "Bonjour tout le monde";

    char *ptr = (char *) malloc (strlen(str) + 1);
    strcpy(ptr, str);

    printf("*ptr : %s\n\n", ptr);

    free(ptr);

    printf ("After free ptr = %p\n", ptr);
    printf ("Content ptr    : %s\n", ptr);
    printf ("Content ptr+8 : %s\n", ptr+8);

    return 0;
}


输出:

*ptr : Bonjour tout le monde

After free ptr = 0x13c7010
Content ptr    : 
Content ptr+8 : tout le monde

是否有人知道答案?

Does someone has the answer?

推荐答案

免费()不需要清除内存,真是不应该,因为这样做会需要时间和覆盖的缓存数据没有普遍要求的好处。

free() is not required to clear memory, and really it shouldn't because doing so would take time and overwrite cached data for no universally required benefit.

这当然允许使用的内部空间为己用。你们看到的可能只是可用内存分配器保持跟踪的副作用。

It's certainly allowed to use the internal space for its own purposes. What you are seeing may be just a side effect of the allocator keeping track of free memory.

这篇关于为什么免费的()只设置8个字节第一为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆