How to implement the c malloc/realloc functions properly?

旧城冷巷雨未停 提交于 2019-12-25 19:09:21

问题


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.

Code:

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

回答1:


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.

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.

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.



来源:https://stackoverflow.com/questions/38951255/how-to-implement-the-c-malloc-realloc-functions-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!