为什么malloc分配的内存空间超出了我的要求? [英] Why does malloc allocate more memory spaces than I ask for?

查看:487
本文介绍了为什么malloc分配的内存空间超出了我的要求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现malloc()分配的内存空间超出了我的要求.

I found that malloc() allocates more memory spaces than I ask for.

struct { void *ptr; int var; } msg;   // 16 bytes (checked by sizeof())

for (int i = 0; i < 100000000; i++)
    malloc(sizeof(msg));

作为上述代码,malloc()实际上每个函数调用分配32个字节(由计算),但是valgrind实际上每个调用仅显示16个字节.

As the aforementioned code, malloc() actually allocate 32 bytes per function call (calculated by top), but valgrind shows only 16 bytes per call indeed.

为什么malloc分配的内存空间超出我的要求,以及如何强制malloc()不要浪费那么多的内存空间?

Why does malloc allocate more memory spaces than I ask for, and how to force malloc() not to waste that much memory spaces?

令人惊讶的是,即使结构为24个字节,它也会分配32个字节,因此我猜想内存空间是浪费的.我不确定malloc()是否应分配32字节的倍数.如果是这样,则浪费了内存空间.

Surprisingly, it allocates 32 bytes also even if the struct is 24 bytes, so I guess that the memory spaces are wasted. I am not sure whether malloc() should allocate a multiple of 32 bytes. If it's true, than the memory spaces are wasted.

已编辑

我已经测试过其他情况.

I've tested for other circumstances.

+---------+---------------------------+
|    n    | memory usage of malloc(n) |
+---------+---------------------------+
|  1 ~ 24 |         32 bytes          |
+---------+---------------------------+
| 25 ~ 40 |         48 bytes          |
+---------+---------------------------+
| 41 ~ 56 |         64 bytes          |
+---------+---------------------------+

如果n不是16 * m + 8m∈ℕ,则内存未完全使用.由于n等于22时的内存对齐方式,一些浪费的内存空间是可以理解的,但是当n等于16时它仍应被视为浪费.在大多数平台上,最小内存的大小访问单位是4个字节或8个字节,那么为什么GCC实现每次增加选择16个字节.

The memory is not fully used if n is not 16 * m + 8, m ∈ ℕ. Some memory spaces wasted are understandable because of memory alignment when n equals 22, but it still should be regarded as wasted when n equals 16. On most of the platforms, the size of minimum memory access unit is 4 bytes or 8 bytes, so why does GCC implementation choose 16 bytes per increase.

推荐答案

malloc()calloc()等分配的任何额外内存(如有)是系统的实现定义方面,而不是C所指定.

Any extra memory, if any, allocated by malloc(), calloc(), etc. is an implementation defined aspect of the system and not specified by C.

检查编译器的规范以确定原因.通常是用于内存管理.

Check your compiler's specification to determined why. Usually it is for memory management.

要强制使用其他分配方案,请重写malloc()或使用您自己的内存分配功能.

To force a different allocation scheme, re-write malloc() or use your own memory allocation functions.

这篇关于为什么malloc分配的内存空间超出了我的要求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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