C Programming language

adplus-dvertising
Dynamic Memory Allocation in C: Allcating and Freeing Memory
Previous Home Next

Allocating memory

We use malloc() function to allocate memory.

void * malloc(size_t size); 

malloc function takes size_t as its argument and returns a void pointer. The void pointer is used because it can allocate memory for any type. The malloc function will return NULL if requested memory couldnt be allocated or size argument is equal 0.

Here is an example of using malloc function to allocate memory:

int* pi;
int size = 5;
pi = (int*)malloc(size * sizeof(int));

sizeof(int) return size of integer (4 bytes) and multiply with size which equals 5 so pi pointer now points to the first byte of 5 * 4 = 20 bytes memory block. We can check whether the malloc function allocate memory space is successful or not by checking the return value.

if(pi == NULL)
{
fprintf(stderr,"error occurred: out of memory");
exit(EXIT_FAILURE);
}

Beside malloc function, C also provides two other functions which make convenient ways to allocate memory.

void *calloc(size_t num, size_t size);
void *realloc(void *ptr, size_t size); 

calloc function not only allocates memory like malloc but also allocates memory for a group of objects which is specified by num argument.
realloc function takes in the pointer to the original area of memory to extend and how much the total size of memory should be.

Freeing memory

When you use malloc to allocate memory you implicitly get the memory from a dynamic memory pool which is called heap. The heap is limited so you have to deallocate or free the memory you requested when you dont use it in any more. C provides free function to free memory.

Here is the function prototype:

void free(void *ptr); 

You should always use malloc and free as a pair in your program to a void memory leak.

Previous Home Next