Search code examples
cif-statementpointersmemory-managementdynamic-memory-allocation

How a pointer be deallocated after it's initialized inside a function or an if-else statement?


I never thought of this but I'm a bit curious but what if I initialize a pointer inside an if-else statement like this?

if (true)
{
    int *p=(int*)malloc (sizeof (int));
}   // Will p be freed here?
// Can't free (p) here since it is not in this scope

I think the code tells pretty much everything about my question... I actually have a thought like this, it is necessary to free(p) at the end of if statement, but what if it's inside a loop?

for (int x=0; x<5; x++)
{
    int *p=(int*)malloc (sizeof (int));
    // Some code here
    free (p);   // Will p deallocated 5 times or just once?
}

Solution

  • In your 1st example, no it won't. You just introduced a memory leak, yikes!

    p is a variable (a pointer) with scope inside the body of the if statement.

    So when we reach the end of that body, p will go out of scope, and you won't have any pointer available to that memory you just dynamically allocated at the start of the if statement's body.

    As a result, you cannot free that memory (since you have no pointer to pass to the free method).

    To fix this code, you should do this:

    if (true)
    {
      int *p = malloc (sizeof (int));
      free(p);
    }
    

    In your 2nd example, p will be allocated one time per loop execution, which is the correct behavior.

    Think in it like this:

    1. 1st loop: We dynamically allocate memory and store a pointer to it in p. De-allocate the memory pointed by p.
    2. 2nd loop: We dynamically allocate memory and store a pointer to it in p. De-allocate the memory pointed by p.
    3. 3rd loop: We dynamically allocate memory and store a pointer to it in p. De-allocate the memory pointed by p.
    4. 4th loop: We dynamically allocate memory and store a pointer to it in p. De-allocate the memory pointed by p.
    5. 5th loop: We dynamically allocate memory and store a pointer to it in p. De-allocate the memory pointed by p.

    PS: Unrelated to what you are asking, but read this: Do I cast the result of malloc? No.