1

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?
}
gsamaras
  • 71,951
  • 46
  • 188
  • 305

1 Answers1

1

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.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • 1
    `p` born inside the `if` statement and will be gone after the `if` statement is executed but the allocated memory still there, and that may results in a memory leak, correct? – LastSecond959 Sep 12 '20 at 16:59
  • 1
    The description: _'Dynamically allocate memory, pointed by `p`'_ is a bit misleading. We do not allocate a memory _pointed by `p`_ here, because `p` has no meaningful value at the moment of allocation. What happens in the code would better be described as 'we dynamically allocate memory and store a pointer to it in `p`'. – CiaPan Sep 12 '20 at 17:05
  • 1
    @LastSecond959 exactly! – gsamaras Sep 12 '20 at 17:11
  • 1
    @CiaPan I'd agree, answer rephrased, tnx! – gsamaras Sep 12 '20 at 17:11