问题描述
我在C的malloc实验和我观察到的malloc是浪费了一些空间,一些内存已经分配后。下面是我用来测试的malloc那块code的
I was experimenting with malloc in C and I have observed that malloc is wasting some space after some memory has been allocated. Below is the piece of code I used to test malloc
#include <stdlib.h>
#include <string.h>
int main(){
char* a;
char* b;
a=malloc(2*sizeof(char));
b=malloc(2*sizeof(char));
memset(a,9,2);
memset(b,9,2);
return 0;
}
在下面的图片的右侧中间的(为了清楚新标签中打开图像),你可以看到内存的内容; 0x804b008是可变的'a'和0x804b018指向的地址是可变的B指向的内存。什么是从0x804b00a 0x804b017之间发生的事情的记忆?问题是,即使我尝试分配 3 * sizeof的(字符)
而不是 2 * sizeof的(字符)
字节内存的内存布局是一样的!那么,有什么我失踪?
In the right-middle of the following picture(open the image in a new tab for clarity) you can see the memory contents;0x804b008 is the address pointed by variable 'a' and 0x804b018 is the memory pointed by variable 'b'. what is happening to memory between from 0x804b00a 0x804b017? The thing is even if I try to allocate 3*sizeof(char)
instead of 2*sizeof(char)
bytes of memory the memory layout is the same! So, is there something I am missing?
推荐答案
的malloc()
是允许的,因为它要浪费尽可能多的空间 - 该标准不指定的任何的有关实现的。你拥有的唯一保证是有关对齐(§7.20.3内存管理功能)
malloc()
is allowed to waste as much space as it wants to - the standard doesn't specify anything about the implementation. The only guarantee you have is about alignment (§7.20.3 Memory management functions):
的指针返回,如果分配成功适当对齐,使得它可以被分配给一个指向任何类型的对象,然后用于访问这样的对象或这样的物体的在分配的空间的阵列(直到空间是显式释放)。
您实现自然会返回你最小8字节对齐的指针。
Your implementation appears to return you minimum-8-byte-aligned pointers.
这篇关于用C的malloc内存分配方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!