In the following code, do I really free the memory occupied by the pointer? If not, how I can free the memory? Here I do not want to delete a
but the pointer.
int a = 1;
int* p;
p = &a;
p = NULL;
In the following code, do I really free the memory occupied by the pointer? If not, how I can free the memory? Here I do not want to delete a
but the pointer.
int a = 1;
int* p;
p = &a;
p = NULL;
No, it merely assigns the pointer value to NULL
.
For your particular example, it looks like a
is a stack variable, so you cannot free
it anyways. You can only free memory by calling delete
on memory which is allocated on the heap using new
.
With respect to the question, "how can I free the memory", memory allocated this way does not usually need to be freed. If you are inside a function, the memory is automatically recycled when the function exits. If the variable is globally allocated, then it is never freed until the end of the program.
Edit (response to OP's edit): The pointer will also go out of scope when the context that it is defined in returns. You cannot explicitly free the pointer unless it was created using new
.
a
is declared on the stack, so you don't have to free it. You must free an object allocated with new
using delete
.
See here for more informations about the heap and the stack.
You need to free
if and only if you had alloc
ated.
Since you have just assigned to a pointer p
, not allocated, you do not need to free.
The variable a is stored in stack not in dynamic memory, we only free the memory which is allocated by us means by sing malloc, calloc, alloc , not by system. And the memory of a is automatically deleted when it goes out of scope