Search code examples
cmemory-leaksrealloc

Under what conditions may this function cause memory leakage?


char *expandspace (char* test) {
    static int i = 0;
    test  = realloc (test, ++i * 100); 
    if(test == NULL) {
        printf("realloc fail");
    }
    return test;
}

Under what conditions may this function cause memory leakage? Is there a way to fix it so it works every time? Thanks.


Solution

  • There's one common but pedantic/artificial remark that many like to do - it goes: don't use the same pointer as realloc parameter and result both. Because in case realloc fails, you have lost the pointer to the original memory.

    But the question you need to ask is: what causes realloc to fail to begin with? In case realloc fails, it means that the heap is full and your program can't continue doing anything meaningful regardless - you will need to exit. So the remark is nonsensical in practice - leaving your programming running in a undefined world where no reliable heap exists is plain dangerous practice.