为什么malloc(1)可用于存储4个字节的整数? [英] Why does malloc(1) work for storing 4 byte integers?

查看:302
本文介绍了为什么malloc(1)可用于存储4个字节的整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,malloc(x)返回一个内存块x个字节长.

所以要存储一个4字节的整数,我会这样做:

    int *p = (int *)malloc(4);
    *p = 100;

因为sizeof(int)为我返回4.

但是,如果我这样做:

    int *p = (int *)malloc(1);
    *p = 100;

它的工作原理完全相同,存储值没有问题.

为什么用malloc()请求的内存量似乎无关紧要? 4字节整数不应该需要malloc(4)吗?

解决方案

如果在您的情况下可行,则只是偶然而已,并且不能保证能正常工作.这是未定义的行为(比较此SO问题),一切都会发生. /p>

您期望发生什么?您的程序崩溃了?

如果您更频繁地调用mallocfree,则可能仍然会发生这种情况. malloc通常占用比请求更多的字节,并使用额外的空间进行管理(所有内存块的链接列表,内存块的大小).如果在分配的块之前或之后写一些字节,则很可能会弄乱内部管理结构,并且随后的freemalloc将会崩溃.

如果malloc在内部始终分配最少n个字节,则仅当您访问字节n + 1时,程序才可能崩溃.同样,操作系统通常仅基于页面来保护内存.如果页面的大小为512字节,并且您的malloc-ed字节位于页面的中间,则您的进程可能能够读写页面的其余部分,并且仅在访问下一个内存页面时才会崩溃.但是请记住:即使这行之有效,这也是不确定的行为.

From what I understand, malloc(x) returns a block of memory x bytes long.

So to store a 4 byte integer, I would do:

    int *p = (int *)malloc(4);
    *p = 100;

Because sizeof(int) returns 4 for me.

However, if I do:

    int *p = (int *)malloc(1);
    *p = 100;

It seems to work exactly the same, with no issues storing the value.

Why does the amount of memory requested with malloc() not seem to matter? Shouldn't a 4 byte integer require malloc(4)?

解决方案

If this works in your case it just works by chance and is not guaranteed to work. It is undefined behavior (compare this SO question) and everything can happen.

What did you expect to happen? Your program crash?

That might still happen if you call malloc and free a bit more often. malloc often takes some bytes more than requested and uses the extra space for Managing (linked list of all memory blocks, sizes of memory blocks). If you write some bytes before or after your allocated block then chances are high that you mess with the internal management structures and that subsequent malloc of free will crash.

If malloc internally always allocates a minimum of n bytes then your program might only crash if you access byte n+1. Also the operating system normally only be protects memory based on pages. If a page has a size of 512 bytes and your malloc-ed byte is in the middle of a page then your process might be able to read-write the rest of the page and will only crash when accessing the next memory page. But remember: even if this works it is undefined behavior.

这篇关于为什么malloc(1)可用于存储4个字节的整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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