More on dynamic memory management
In this session, we will explore the dynamic memory allocation and deallocation in C programming. We will discuss the use of the malloc and free functions, the advantages and disadvantages of dynamic memory allocation, and various pitfalls to watch out for. Hang on as we dive deep into the world of malloc and free and learn how to effectively manage memory in C programming.
Before we have a look at static and dynamic memory allocation, What exactly is memory allocation in the first place?
Memory allocation is the process of allocating physical or virtual memory space to computer programs and services. It divided into two.
- Static memory allocation.
- Dynamic memory allocation.
Below are the major difference between the two.
| Dynamic Memory allocation | Static Memory allocation |
|---|---|
| Memory is allocated at run time | Memory is allocated at compile time |
| Memory can be increased while executing program | Memory can't be increased while executing program |
| Used in Linked List | Used in Arrays |
| Allocation is done from the Heap Memory | Allocation is done from the Stack Memory |
| Allocated memory can be released and used again if not required anymore | Memory allocated cannot be reused |
| More Efficient memory management method | Less Efficient memory managenent method |
Dynamic memory allocation in C using malloc()
So What exactly is malloc() and why is it important?
The malloc() function is used to allocate a certain amount of memory durign execution of a program.
It will request a block of memory ( as specified in the malloc call) from the heap and once the request is granted, the Operating system will reserve the requested block of memory and malloc will return a pointer to the reserved space.
When the amount of memory is no longer needed anymore, you need to return it to the operating system by calling free()
The prototype for the malloc funtion is void *malloc(size_t size); where size is the amount of memory you want to allocate in bytes
The malloc funtion returns a void pointer, which begs the next question, Should I cast the result of malloc?
Memory allocation using calloc()
How to use calloc
The basic syntax when using calloc is
ptr = (cast-type*)calloc(n, element-size);
Difference between calloc and malloc
- exit(3)
- calloc
- malloc
- free
- How to use the
exitfunction - What are the functions ``calloc
andrealloc``` from the standard library and how to use them
