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?
}
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:
p
. De-allocate the memory pointed by p
.p
. De-allocate the memory pointed by p
.p
. De-allocate the memory pointed by p
.p
. De-allocate the memory pointed by p
.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.