gpt4 book ai didi

c - C中的malloc内存分配方案

转载 作者:太空狗 更新时间:2023-10-29 15:14:23 25 4
gpt4 key购买 nike

我在 C 中试验 malloc,我观察到 malloc 在分配了一些内存后浪费了一些空间。下面是我用来测试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(char) 而不是 2*sizeof(char) 字节的内存,内存布局也是一样的!那么,我缺少什么吗?

gdb interface

最佳答案

malloc() 允许浪费尽可能多的空间 - 该标准没有指定关于实现的任何内容。您唯一的保证是对齐(§7.20.3 内存管理函数):

The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly deallocated).

您的实现似乎会返回至少 8 字节对齐的指针。

关于c - C中的malloc内存分配方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6389120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com