x
Loading
 Loading
Hello, Guest | Login | Register

Dynamic Memory Allocation — Part I

This month we’re going to examine a topic that is probably familiar to those of you who have any experience with programming — dynamic memory allocation. In any programs of significant heft, dynamic memory management is a necessity. You are probably experienced with the standard C functions malloc() and free(), and we’ll do a brief recap of those memory allocation and deallocation functions. Following that, we will look at how memory allocation in Linux actually works.

This month we’re going to examine a topic that is probably familiar to those of you who have any experience with programming — dynamic memory allocation. In any programs of significant heft, dynamic memory management is a necessity. You are probably experienced with the standard C functions malloc() and free(), and we’ll do a brief recap of those memory allocation and deallocation functions. Following that, we will look at how memory allocation in Linux actually works.

Memory Allocation Functions

There are three standard C functions that you can use to allocate memory — malloc() , calloc() , and realloc() . Their prototypes, as defined in <stdlib.h> , are:

void* calloc (size_t nmemb, size_t size); void* malloc (size_t size); void* realloc (void *ptr, size_t size); 

malloc() is the simplest of the allocators. It simply takes an argument specifying the size of the memory block that you wish to allocate and returns a pointer to a block of memory of that size. calloc() takes in two arguments, a number of elements ( nmemb ), and a size for each element ( size ). The total size allocated by a call to calloc() will be (nmemb * size) bytes. Also, calloc() actually sets all the memory it returns to NULL . In contrast, there are no guarantees regarding the values stored in the memory returned my malloc() .

realloc() is used to reallocate a section of memory that has been previously allocated. Notice that…

Please log in to view this content.

Not Yet a Member?

Register with LinuxMagazine.com and get free access to the entire archive, including:

  • Hands-on Content
  • White Papers
  • Community Features
  • And more.
Already a Member?
Log in!
Username

Password

Remember me

Forgotten your password?
Forgotten your username?
Read More
  1. Helpful Tools for Software Developers
  2. The Github Hall of Fame
  3. Book'em, Github.
  4. This Week on Github: Stupid Ruby Tricks
  5. A Veritable Scatter Shot!
Follow Linux Magazine
Rackspace