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:
- 1st loop: We dynamically allocate memory and store a pointer to it in
p
. De-allocate the memory pointed by p
.
- 2nd loop: We dynamically allocate memory and store a pointer to it in
p
. De-allocate the memory pointed by p
.
- 3rd loop: We dynamically allocate memory and store a pointer to it in
p
. De-allocate the memory pointed by p
.
- 4th loop: We dynamically allocate memory and store a pointer to it in
p
. De-allocate the memory pointed by p
.
- 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.