-1

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();
    }
subado512
  • 115
  • 2
  • 7
  • I'm afraid you have a long way to go before you have a real OS. – chqrlie Aug 15 '16 at 07:54
  • Your `free()` function doesn't inspire confidence in your understanding of C. – EOF Aug 15 '16 at 08:06
  • Yeah your right, I have no idea, I started programming in higher level languages. Only know c because of c++. I am forced to use c because it is an OS. Wish I could use golang or something like that. – subado512 Aug 15 '16 at 08:17
  • There are many beginner mistakes in this code and most of it does not make any sense. To begin with, [read this](http://stackoverflow.com/questions/4570366/pointer-to-local-variable). And are you programming in C or C++? It looks like C++ strings. – Lundin Aug 15 '16 at 08:19
  • A readme in the topic: https://github.com/emeryberger/Malloc-Implementations – Koshinae Aug 15 '16 at 10:42
  • The string is : typedef char *string, so no it isn't a c++ string. – subado512 Aug 16 '16 at 08:19

1 Answers1

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483