Skip to content
Physics and Astronomy
Home Our Teaching Resources C programming Common mistakes
Back to top
On this page
Contents

Common mistakes with memory allocation

Dereferencing a pointer without allocating some memory for it

This is the ultimate memrory allocation error and will lead to disaster.

Bad Good
 
 

Not checking for NULL return from malloc()

Bad Good
 
 
Better
 
 

Using malloc() instead of an ordinary array when the array is not needed after the function returns

  • Ordinary array declaration is fast and the memory is automatically released when the function returns.
  • Dynamic memory allocation is slow and is permenant until freed.

So:

  • Use normal arrays when the array is not needed after the function returns.
  • Use dynamic allocation when it is.
Poor Better
 
 
The first version has more ways to go wrong, we might forget to call free(), and is also slower. (However, until C99 programmers had no choice as array sizes had to be declared at compile time.) It's not unknown for the speed of some programs to be dominated by calls to malloc().

Using an ordinary array instead of malloc() when the array is needed after the function returns

This is the reverse of the previous one but is much more serious as the program will give the wrong answers or crash.

Bad Better
 
 
Log in
                                                                                                                                                                                                                                                                       

Validate   Link-check © Copyright & disclaimer Privacy & cookies Share
Back to top