用C的malloc内存分配方案 [英] malloc memory allocation scheme in C

查看:174
本文介绍了用C的malloc内存分配方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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):

的指针返回,如果分配成功适当对齐,使得它可以被分配给一个指向任何类型的对象,然后用于访问这样的对象或这样的物体的在分配的空间的阵列(直到空间是显式释放)。

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字节对齐的指针。

Your implementation appears to return you minimum-8-byte-aligned pointers.

这篇关于用C的malloc内存分配方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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