如何正确实现c malloc/realloc函数? [英] How to implement the c malloc/realloc functions properly?

查看:424
本文介绍了如何正确实现c malloc/realloc函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing my own OS and had to implement my own malloc realloc functions. However I think that what I have written may not be safe and may also cause a memory leak because the variable isn't really destroyed, its memory is set to zero, but the variable name still exists. Could someone tell me if there are any vulnerabilities in this code? The project will be added to github soon as its finished under user subado512.

代码:

 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;
}

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

Context in which code is used : Bit of pseudo code to increase readability

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

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

推荐答案

使用由malloc返回的指针的行为是 undefined :您正在使用自动返回数组的地址存储期限.

The behaviour on your using the pointer returned by your malloc is undefined: you are returning the address of an array with automatic storage duration.

作为一个粗略的开始,请考虑使用static char数组对您的内存池进行建模,并将其分段返回给调用方;建立当前正在使用的数组的表.请注意,您必须在此处使用 alignment 做一些聪明的事情,以确保返回的void*满足 any 类型的对齐要求. free然后只不过是您在该表中释放记录而已.

As a rough start, consider using a static char array to model your memory pool, and return segments of this back to the caller; building up a table of that array that is currently in use. Note that you'll have to do clever things with alignment here to guarantee that the returned void* meets the alignment requirements of any type. free will then be little more than your releasing a record in that table.

请注意,典型的C运行时库使用的内存管理系统非常复杂.考虑到这一点,一定要感谢您的工作可能仅仅是一项良好的编程练习.

Do note that the memory management systems that a typical C runtime library uses are very sophisticated. With that in mind, do appreciate that your undertaking may be little more than a good programming exercise.

这篇关于如何正确实现c malloc/realloc函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆