With dynamic memory allocation, while the program is running, the program requests more memory from the computer. If there's enough memory available, the computer will grant the program the right to use the amount it requests.

Dynamic Memory and Pointers

When we ask the computer for memory dynamically, what do you think it gives us? That's right, an address. When we ask the computer for memory, it goes and sees what memory it has available. Assuming it has enough to give us, the operating system will set aside the amount of memory we requested and give us that memory's address so that we can then use it. How do we store an address? In a pointer.

The functions we'll use to grab dynamic memory return a pointer to that memory (or if for some reason we couldn't get the memory we requested, they'll return the NULL value). We can then use that memory through the pointer just like it was ours to begin with, setting values in the memory, getting values from the memory, etc.

As this tutorial is primarily on pointers, we won't delve too much into memory allocation here as the point of this section is simply to point out that you can do dynamic allocation. However, we will still show you a few basics.

Allocating memory

Allocating memory in C primarily revolves around two functions: malloc() and free(). malloc() is used to allocate memory (to request it) and free() is used to give it back. In C++, the operators new and delete are used to accomplish similar tasks, however due to the additional complexity surrounding these operators, we will not discuss them here (refer to the C++ SparkNote for more information).

malloc()

So how exactly do we ask the system for memory? With the function malloc(). There are other functions as well, all part of the malloc() family, but we'll only be discussing malloc() here as it is the most common. malloc() takes a single argument, the number of bytes to allocate, and returns a pointer to the allocated memory if the allocation was successful, or NULL otherwise. For example, to allocate a chunk of memory 1024 bytes in length (1KB), we would use the instruction malloc(1024).