使malloc功能不能正常工作?

时间:2019-11-08 14:43:07

标签: c malloc

嗨,我写了一个简单的malloc和free函数。这个想法基本上来自“ C编程语言”。现在我有问题,例如如果我分配3次并以相同的顺序释放它。我的allocp快要用完了,但是整个内存都可用了。我现在给你我的例子。我的问题是3免费。就像当我释放4、3、2没问题时一样,因为您以正确的顺序释放了allocp,但是我不知道如何解决我的问题。

有什么想法吗?

感谢您的帮助:)

#include "mystdlib.h"
#include <stdio.h>
#define ALLOCSIZE 1048576 /* Groeße des verfuegbaren Speichers */

static char allocbuf[ALLOCSIZE]; /* Speicher fuer mymalloc */
static char *allocp = allocbuf; /* next free position */

void *mymalloc(size_t size) {
    if(allocp + size <= allocbuf + ALLOCSIZE) {
        allocp += size;
        return (allocp - size);
    }
    else {
        return NULL;
    }

}

void myfree(void *ptr) {
    if(ptr >= (void*)allocbuf && ptr < (void*)allocbuf + ALLOCSIZE) {
        allocp = ptr;
    }
}

int main(){
    char *buf1 = mymalloc(900000);
    if (buf1 == NULL) {
        printf("Error 404, allocated memory not found...\n");
        return -1;
    }
    myfree(buf1);

    char *buf2 = mymalloc(500000);
    char *buf3 = mymalloc(400000);
    char *buf4 = mymalloc(300000);

    if (buf2 == NULL || buf3 == NULL) {
        printf("Fix your mymalloc!\n");
        return -1;
    }

    if (buf4 == NULL) {
        printf("This was supposed to happen. Very good!\n");
    } else {
        printf("Nope. That's wrong. Very wrong.\n");
        return -1;
    }

    myfree(buf2);
    myfree(buf3);
    myfree(buf4);

    char *buf5 = mymalloc(900000);
    if (buf5 == NULL) {
        printf("You got so far, but your error free journey ends here. Because an error occured.\n");
        return -1;
    }

    char *buf6 = myrealloc(buf5, 500000);
    myfree(buf6);

    printf("Congrats, you passed all tests. Your malloc and free seem to work\n");
}

0 个答案:

没有答案