Dynamic Memory management basics in c programming

Reading Time: 5 minutes

Today in this article, we are going to discuss the dynamic memory management basics in C programming language. If you ever wonder what calloc, malloc, realloc and free etc. stands for, keep reading and you’ll get a sound knowledge about them and their usages. If you are new to C programming, I suggest you first look at https://www.rukbook.com/c-program-to-create-a-simple-calculator-explained/

What are we going to learn?

  • What is dynamic memory management in C?
  • stdlib.h file and its usage in memory management.
  • malloc and its usage
  • calloc and its usage
  • realloc and its usage
  • free and its usage

What is dynamic memory management in C?

Whenever we run a computer program, it needs memory to carry out its tasks. This memory stores mainly 2 things,

  • Data (Variables, structures etc.)
  • Instructions (Program code)

To store variables of known size (for example an int array of known size), we can declare them the usual way. That method is static memory allocation.

But when we don’t know how large or small a particular variable can be, we have to use dynamic memory allocation. By dynamic memory allocation, we can allocate memory at runtime (while our program is running).

Trust me, it’s not as hard as it sounds. If you keep reading, I’m sure you’ll get to an “Ah ha!” moment by understanding them well. Depending on the operating system, the available amount of RAM will be different even for the same amount of physical RAM.

What is stdlib.h?

stdlib stands for “standard library”. This header file contains several methods important for memory management purposes in the C programming language.

These methods are,

  • malloc
  • calloc
  • realloc
  • free

NOTE :- some compilers may need to include malloc.h file as well.

What is malloc?

malloc allocates a memory block with a size given in bytes. This takes place in the RAM of the computer while the program is running.

malloc allocates a group of bytes.

malloc’s protoype is,

void *malloc(size_t num);

The size_t is an unsigned integer datatype.

What happens in this code is, a memory block of num bytes is allocated in RAM. A pointer to the first byte is returned from the malloc function.

The malloc function returns NULL if,

  • num is 0
  • cannot allocate requested memory
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    char *str;

    str = (char *) malloc(20);
    strcpy(str, "rukbook");

    printf("%s\n", str);
    return 0;
}

Line 1 includes stdio.h so that we can use the printf function.

In line 2, stdlib.h is included so that we can use malloc function.

Line 3 includes string.h so that we can use strcpy function. This functions copies the string “rukbook” to the character pointer variable str.

In line 8, we have the malloc function in use. Since we have used it here to allocate memory for a string, the return type is a (char *), unlike the void in the above mentioned prototype. Here we have used the value 20 instead of the variable num. So ultimately, the line 8 says to allocate 20 bytes in a memory block, and assign the returned pointer to the str pointer.

What is calloc?

calloc also allocates memory (similar to malloc), but additionally calloc clears all the allocated memory (set memory to 0), if the allocation is successfull. This does not happen in malloc.

A pointer to the first byte is returned from the calloc function.

calloc allocates a group of objects.

calloc’s function prototype is,

void *calloc(size_t num, size_t size);

Here, num is the number of objects to allocate. And size is the number of bytes of each object.

The calloc function returns NULL if,

  • either num or size is 0
  • failed allocation

malloc and calloc comparison

What is realloc?

realloc resizes a memory block (we could have created this memory block using either malloc or calloc).

realloc’s function prototype is,

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

ptr is a pointer to the original memory block. size is the new size in bytes.

Several possible outcomes when implementing realloc function are,

  • If enough space available to expand in the current memory block, size bytes are added to the memory block and returns the pointer ptr.
  • If not enough space available to expand in the current memory block, data are copied to a new block. The old block is freed. The function returns a pointer to the new block.
  • If not enough space available to expand in the current memory block and also no space for a new block, the function returns NULL. Nothing happens to the original memory block.
  • If ptr argument is NULL, realloc acts like malloc.
  • If the size argument is 0, the memory block pointed by ptr is freed. The function returns NULL.

What is free?

The dynamic memory pool or heap is a limited space. Therefore when a particular dynamically allocated memory block is no longer needed by the program, it should be deallocated or freed.

free is used to clear a memory block. This memory block was the one allocated using either malloc or calloc.

free function prototype is,

void free(void *ptr);

This function frees the memory pointed to by ptr pointer.

If ptr is NULL, this function does nothing.

In NVIDIA CUDA C, this free method is found as cudaFree. CUDA C is a special extended version of C programming language, used in various 3D applications.

in C++, a similar purpose is achieved by delete keyword.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    char *str;

    str = (char *) malloc(20);
    strcpy(str, "rukbook");

    printf("%s\n", str);

    str = (char *) realloc(str, 30);
    strcat(str, ".com");

    printf("%s\n", str);

    free(str);

    return 0;
}

This code is an extension for the earlier code we had for malloc, and in this code, we have used realloc and free. This can be considered as a place where we have used many dynamic memory management basics available in C.

In line 13, the size of the memory block pointed to by the str pointer is set to 30 bytes. (earlier this size was 20 bytes). The returned pointer is set to str variable.

In line 14, a string concatenation is performed and the string “.com” is added to the end of the string stored (“rukbook“) at the address pointed to by the str pointer. The result will be a string “rukbook.com“.

Line 18 frees (clears) the memory block pointed to by the str pointer variable so that space can be used for another allocation in the future.

Conclusion

That’s it! and those are the basics that you should know about dynamic memory management in C and later you’ll realize that in programming languages like C++, this knowledge comes in handy, with some slight modifications.

Like rukbook.com so far? Chances are, you’ll like rukbook on YouTube (coming soon)! Click the button below to stay subscribed ahead of time!

In the next article, we will have a look at memset, memcpy and memmove functions, which are used to manipulate memory blocks.

Did you enjoy this article? Why not share it with your friends and connections? It helps spread the word about rukbook and it means a lot! Thanks for reading. Subscribe to rukbook.com mailing list by just entering your email below!

Subscribe

* indicates required
4.3 3 votes
Article Rating

Leave a comment. We love your feedback.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x