Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NULL pointer is the same as deallocating it?

Tags:

I was working on a piece of code and I was attacked by a doubt: What happens to the memory allocated to a pointer if I assign NULL to that pointer?

For instance:

A = new MyClass();

{...do something in the meantime...}

A = NULL;

The space is still allocated, but there is no reference to it. Will that space be freed later on, will it be reused, will it remain on stack, or what?

like image 868
André Moreira Avatar asked Nov 24 '09 11:11

André Moreira


People also ask

What is called null pointer?

A null pointer has a reserved value that is called a null pointer constant for indicating that the pointer does not point to any valid object or function. You can use null pointers in the following cases: Initialize pointers. Represent conditions such as the end of a list of unknown length.

Is Delete same as Nullptr?

@Omega delete pointer; pointer = nullptr. just deletes the pointer. setting it to null after deleting is fine. Setting null to a pointer is not same as deleting.

What is void pointer and null pointer?

The null pointer is basically used in a program to assign the value 0 to a pointer variable of any data type. The void pointer, on the other hand, has no value assigned to it and we use it to store the addresses of other variables in the program- irrespective of their data types.

What does it mean to free a pointer?

Freeing the allocated memory deallocates it and allows that memory to be used elsewhere while the pointer to where the memory was allocated is preserved. Setting a pointer to the allocated memory to NULL does not deallocate it.


2 Answers

This is a classic leak. As you say, the memory remains allocated but nothing is referencing it, so it can never be reclaimed - until the process exits.

The memory should be deallocated with delete - but using a smart pointer (e.g. std::auto_ptr or boost::shared_ptr (or tr1::shared_ptr) to wrap the pointer is a much safer way of working with pointers.

Here's how you might rewrite your example using std::auto_ptr:

std::auto_ptr a( new MyClass() );

/*...do something in the meantime...*/

a.reset();

(Instead of the call to reset() you could just let the auto_ptr instance go out of scope)

like image 192
philsquared Avatar answered Oct 17 '22 01:10

philsquared


Under most circumstances, that will cause a memory leak in your process. You have several options for managing memory in C++.

  1. Use a delete to manually free memory when you're done with it. This can be hard to get right, especially in the context of exception handling.

  2. Use a smart pointer to manage memory for you (auto_ptr, shared_ptr, unique_ptr, etc.)

  3. C++ does not come with a garbage collector, but nothing prevents you from using one (such as the Boehm GC) if you want to go down that route.

like image 40
Ferruccio Avatar answered Oct 17 '22 01:10

Ferruccio