如何通过指针算法访问内存块的头?

问题描述 投票:0回答:1

我正在处理一个家庭作业问题,其中包括制作一个用户可以用来管理内存的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()函数是0x87a3008(由于8字节对齐有意义)

当我做指针运算时,就像在标题的变量位置一样,placeOfHeader的内存位置是0x87a3007。

c pointers memory-management heap-memory
1个回答
0
投票

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)
© www.soinside.com 2019 - 2024. All rights reserved.