如何正确实现c malloc / realloc功能?

时间:2016-08-15 07:51:48

标签: c operating-system kernel systems-programming

我正在编写自己的操作系统,并且必须实现自己的malloc realloc函数。但是我认为我写的内容可能不安全,也可能导致内存泄漏,因为变量并未真正被破坏,其内存设置为零,但变量名仍然存在。有人能告诉我这个代码中是否有任何漏洞?该项目将在用户subado512下完成后立即添加到github。

代码:

 void * malloc(int nbytes)
{
    char variable[nbytes];
    return &variable;
}
void * free(string s) {
    s= (string)malloc(0);
    return &s;
}

void memory_copy(char *source, char *dest, int nbytes) {
    int i;
    for (i = 0; i < nbytes; i++) {
        *(dest + i) = *(source + i);             //    dest[i] = source[i]
    }
}
void *realloc(string s,uint8_t i) {
    string ret;
    ret=(string)malloc(i);
    memory_copy(s,ret,i);
    free(s);
    return &ret;
}

使用代码的上下文:用于提高可读性的伪代码位

    string buffstr = (string) malloc(200);
    uint8_t i = 0;
    while(reading)

    {
        buffstr=(string)realloc(buffstr,i+128);
        buffstr[i]=readinput();
    }

1 个答案:

答案 0 :(得分:1)

使用malloc返回的指针时的行为是未定义:您将返回具有自动存储持续时间的数组地址。

作为一个粗略的开始,请考虑使用static char数组来建模内存池,并将其返回给调用者;构建当前正在使用的该数组的表。请注意,您必须在此处使用 alignment 做一些聪明的事情,以确保返回的void*符合任何类型的对齐要求。 free只会比您在该表中发布的记录多一点。

请注意,典型的C运行时库使用的内存管理系统非常复杂。考虑到这一点,请欣赏您的承诺可能只是一个很好的编程练习。

相关问题