0

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;
Shibli
  • 5,879
  • 13
  • 62
  • 126

4 Answers4

2

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.

merlin2011
  • 71,677
  • 44
  • 195
  • 329
2

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.

Community
  • 1
  • 1
DCMaxxx
  • 2,534
  • 2
  • 25
  • 46
  • or `malloc` with `free` – clcto Apr 03 '14 at 00:59
  • @clcto It's C++ so there's no reason to be using `malloc` and `free`. – Carey Gregory Apr 03 '14 at 01:01
  • 1
    @CareyGregory 'there's no reason' is misleading. There are some situations where `malloc` would be preferred over `new`, specifically for performance reasons (or C interop). It's much faster to use malloc for a simple buffer, as it doesn't need to initialize any memory returned from it, so if using it in high performance scenarios where you write to the data before ever reading from it, it may make sense to use malloc. – Richard J. Ross III Apr 03 '14 at 01:05
  • @RichardJ.RossIII Well, there are corner cases for everything, but with someone just learning C++ I would be confident telling them there is never a good reason to use `malloc`. – Carey Gregory Apr 03 '14 at 01:07
  • 1
    @RichardJ.RossIII - You may still need `malloc`/`free` to interact with C code, but you don't need `malloc` to allocate uninitialized memory, you can call `operator new` directly. i.e. `void* p = operator new(100)` in C++ will do the same thing as `void* p = malloc(100)` in C. – Ferruccio Apr 03 '14 at 01:13
0

You need to free if and only if you had allocated.

Since you have just assigned to a pointer p, not allocated, you do not need to free.

Arun
  • 19,750
  • 10
  • 51
  • 60
0

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

psk1801
  • 21
  • 1
  • 6