gpt4 book ai didi

c - 当剩余内存超过一定大小时,我的自定义 malloc 函数崩溃

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

<分区>

我尝试在 C 中创建自己的 malloc 函数,使用数组作为我将要使用的内存。但是当剩余内存大小超过一定位数时,程序崩溃并提示“抛出异常:写入访问冲突。”

我把内存分成 block 。每个 block 都会有一个小的元数据 block ,它保存了 block 的大小以及它是空闲的还是被占用的(一开始,整个内存阵列是一个大块)。然后我的 malloc 找到第一个具有足够大小的内存块并使用它(或它的一部分)。

问题是:例如,如果我初始化一个大小为 20000 字节的数组,我的 malloc 将仅在数组中剩余的空闲字节为 17708 或更多时才起作用。

#include <stdio.h>

char memory[20000];

struct block {
unsigned int size;
int free;
struct block* next;
};

struct block* freeList = (void*)memory;

void initialize() { /
freeList->size = 20000 - sizeof(struct block);
freeList->free = 1;
freeList->next = NULL;
}

void split(struct block* fitting_slot, unsigned int size) {
struct block* new = (void*)(fitting_slot + size + sizeof(struct block));
unsigned int temp = (fitting_slot->size) - size - sizeof(struct block);
printf("Remaining memory size is %d\n", temp);

new->size = temp; // this is where program crashes
new->free = 1;
new->next = fitting_slot->next;
fitting_slot->size = size;
fitting_slot->free = 0;
fitting_slot->next = new;
}


void* MyMalloc(unsigned int noOfBytes) {
struct block* curr;
void* result;
if (!(freeList->size)) {
initialize();
}
curr = freeList;

while ((((curr->size) < (noOfBytes + sizeof(struct block))) || ((curr->free) == 0)) && (curr->next != NULL)) {
curr = curr->next;
}
printf("From the free memory of size : %d\n", curr->size);
printf("We will occupy this size : %d\n", noOfBytes + sizeof(struct block));

if ((curr->size) == (noOfBytes + sizeof(struct block))) {
curr->free = 0;
result = (void*)(++curr);
printf("Exact fitting block allocated\n\n");
}
else if ((curr->size) > (noOfBytes + sizeof(struct block))) {
split(curr, noOfBytes);
result = (void*)(++curr);
printf("Fitting block allocated with a split\n\n");
}
else {
result = NULL;
printf("Sorry. No sufficient memory to allocate\n\n");
}
return result;
}

int main(){
unsigned int size = 2270 * sizeof(char);
char* k = (char)MyMalloc(size);
printf("Success\n");
}

如果“size”的数字是 2269 或更低,程序可以正常工作。

如果 main 中的“size”数为 2270 或更高,则程序崩溃new->size = temp 函数 split() 说“抛出异常:写入访问冲突。”

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