Alex Rivera | Logout

What is the difference between freeing the pointer and assigning it to NULL?

Asked 2010-03-12T06:00:12.847
26

Could somebody tell me the difference between:

int *p;
p=(int*)malloc(10*sizeof(int));
free(p);

or

int *p;
p=(int*)malloc(10*sizeof(int));
p=NULL;
Edit
Report

2 Answers

12

p is pointer (to a block allocated dynamically in memory ["on the Heap"])
This means that p is a variable which contains the address in memory of a particular block (or some particular size, in the example a block big enough to hold 10 integers).

free(p); instructs the memory management logic (of the C Runtime) that the memory previously occupied by the block which p points to can be reused.

p = NULL; sets the value of p to NULL (the address it formerly contained is lost) but the block in memory it pointed too is still considered in use.

There can be some confusion because in languages such as Java, C#, Python etc. merely assigning the variable to NULL (or to another address for that matter), will automatically free the underlying memory (assuming no other references to this address exist in other live variables).

This is not the case in C or C++, leading to errors like the following:

  free(p);
  // possibly some some code etc.
  // later:
  p[6] = 'a';  // <<---  Ouch we're modifying whatever new variable is there !!!

or

  // didn't call free(p)
  p = NULL;
  // now the memory allocated for p is held in memory even though it
  // is not going to be used (assuming no copies of p or of pointers to part
  // of that block were made.

The latter case is only wasteful of resources, the former can lead to hard to find bugs.

That's why a typical C idiom is:

   free(p);
   p = NULL;
answered 2010-03-12T06:03:36.757
1

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.

If you are using an implementation that uses a heap-based malloc, debug something that allocates, uses and frees memory, and do the same to something that allocates, uses, and sets the pointer to the memory to NULL.

Memory management is implementation-dependent (see http://en.wikipedia.org/wiki/Malloc#Implementations).

answered 2010-03-13T01:36:40.987

Your Answer