c - 如何正确实现c malloc/realloc函数?

标签 c operating-system kernel systems-programming

我正在编写自己的操作系统,并且必须实现自己的 malloc realloc 函数。不过我认为我写的可能不安全,也可能导致内存泄漏,因为变量并没有真正销毁,它的内存被设置为零,但变量名仍然存在。有人能告诉我这段代码是否存在漏洞吗?该项目完成后将立即添加到 github,用户为 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;
}

使用代码的上下文:一些伪代码以增加可读性

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

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

最佳答案

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

作为一个粗略的开始,请考虑使用 static char 数组来模拟内存池,并将其片段返回给调用者;建立当前正在使用的数组的表。请注意,您必须在此处巧妙地使用对齐,以保证返回的void*满足任何类型的对齐要求。 free 就相当于您释放该表中的一条记录。

请注意,典型的 C 运行时库使用的内存管理系统非常复杂。考虑到这一点,请务必意识到您的工作可能只不过是一次很好的编程练习。

关于c - 如何正确实现c malloc/realloc函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38951255/

相关文章:

memory-management - 有人可以解释一下操作系统中的分页吗?

python - 使用 os.execlp 时,为什么 `python` 需要 `python` 作为 argv[0]

linux - "Switching from user mode to kernel mode"是一个错误的概念

c - 需要帮助调试段错误

c# - 如何为 C# 应用程序创建 RPC 服务器

c - Windows 中进程的最短保证时间是多少?

android - 如何使 ftrace function_graph 跟踪器可以使用 linux 内核函数?

c - gcc 在 lib 中找不到函数

c++ - 如何在 C++ 中读取系统信息?

linux - 从用户空间的程序调用内核模块函数