【问题标题】:How to access header for memory block via pointer arithmetic?如何通过指针运算访问内存块的标头?
【发布时间】:2019-08-18 15:32:41
【问题描述】:

我正在处理一个家庭作业问题,其中包括制作一个用户可以用来管理内存的 c 程序。本质上,我们试图以我们自己的方式模仿 malloc() 和 free() 所做的事情。我目前正在处理的函数是一个 initmemory(int size) 函数,它分配用户将使用的整个块,并且从该块中,随着程序调用 myalloc() 函数(基本上是我们的 malloc 版本),将分配较小的块())。我的问题是,我试图访问整个块的标题部分以保存块的大小和分配状态,但是当我尝试执行指针运算时,我最终只移动了一位。如何访问标头以使用指针变量 startOfMemory 保存块的大小和分配状态

void initmemory(int size){
    printf("this is the initial size: %d\n", size);
    //realSize = size + initial padding + anchorHeader + sentinelBlock
    int realSize = size + 12;
    printf("I am the new realSize: %d\n", realSize);
    //checks how many remainders are left
    int check = realSize % 8;
    printf("this is the value of check: %d\n", check);
    //will only change realSize if check is not zero
    if(check != 0){
        //adds enough bytes to satisfy 8-byte alignment 
        realSize = realSize + (8 - check);
        /*
         * this is only to make sure realSize is 8-byte aligned, it should not run
         * unless the above code for some reason does not run
         */

        check = realSize % 8;
        while(check != 0){
            realSize = realSize + (8-check);
            check = realSize % 8;
            printf("I'm in the while check loop");
        }
    }
    // initializes the memory to be allocated. 
    void *startOfMemory = malloc(realSize);
    void *placeOfHeader = startOfMemory - 1;

    printf("my memory location is at: %p\n", startOfMemory);
    printf("my realSize is: %d\n", realSize);
    printf("memory location of placeOfHeader: %p\n", placeOfHeader);
    free(startOfMemory);

}
int main(){
    initmemory(5);
    return 0;
}

调用 malloc() 函数的 startOfMemory 的内存位置是 0x87a3008(由于 8 字节对齐,这很有意义)

当我做指针运算时,如在header的变量place中,placeOfHeader的内存位置在0x87a3007。

【问题讨论】:

  • 嗯,0x87a3008 - 1 = 0x87a3007。究竟是什么让你感到惊讶?您期望什么以及为什么?
  • @Ctx 好吧,我想访问前 4 个字节以添加内存块的大小和分配状态,我的印象是,如果我进行了您突出显示的指针运算,它会将我移回 4 个字节。只有当内存块被分配为数组时?还是因为指针类型为void?
  • int32_t *p = (int32_t*)startOfMemory-1;,将向前移动4个字节,指针运算与指针类型有关int64_t *p = (int64_t*)startOfMemory-1; 将向前移动 8 个字节。

标签: c pointers memory-management heap-memory


【解决方案1】:

placeOfHeader 不在分配区域的某个位置。 你可能想写这样的东西。

//alloc(realSize)
void *placeOfHeader = malloc(realSize);
*((size_t*)placeOfHeader) = realSize;
void* startOfMemory = (size_t*)placeOfHeader + 1;
return startOfMemory;

//free(startOfMemory)
void* placeOfHeader = (size_t*)startOfMemory - 1;
size_t realSize = *((size_t*)placeOfHeader);
free(placeOfHeader)

【讨论】:

    猜你喜欢
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    相关资源
    最近更新 更多