Search code examples
cmemory-managementmallocfree

malloc / free. can read from freed memory


Here how i malloc memory

char *convertToPostfix(char **infixExpr)
{
    char *postfixExpr = (char *) malloc(strlen(*infixExpr) * sizeof(char) * 2);
    ...
    return postfixExpr;
}

Here how i use this memory:

char *subexpr = convertToPostfix(infixExpr);
free(subexpr);
while (*subexpr) 
    postfixExpr[i++]=*subexpr++;

Why does this program work normally after free(subexpr); I mean why is it possible to iterate in while after freeing?

And am i doing everything right working in such way, when function returns some memory, which is freed in another context?


Solution

  • Your program exhibits undefined behaviour. In short anything can happen, including your program appearing to work.

    It's quite common that implementations of malloc/free do not return memory blocks to the underlying OS immediately after you call free. This is done for performance reasons. The next call to malloc may well be most efficiently be handled by returning a pointer to the block that you just freed and therefore re-using it. At this point, in your code, there would be two pointers referring to the same block of memory and who knows what would happen next.