Dynamic Memory Allocation in C
Let's take a step back to what Memory is.
what is Memory?
Memory is a sizable collection of bytes. In programming, we refer to RAM (Randon Access Memory) when talking about memory. The RAM is made up of different areas.
Stack which is managed automatically by the compiler and where local variables are stored.
Heap which is managed by a programmer. it is a pile of memory space that is available to programmers to allocate and de-allocate.
Now let's understand what Memory Allocation is in Programming.
Memory Allocation is the process of allocating or assigning a space to a computer application. In C programs two kinds of memory allocation are supported through its variables.
static allocation which is a process in which a fixed amount of memory allocates during compile time. this happens when you declare a static or global variable. Each static or global variable defines one block of space, of a fixed size. The space is allocated once when your program is started and is never freed.
Automatic allocation when you declare an automatic variable it results in automatic allocation such as a function argument or local variables. The space for an automatic variable is allocated when the compound statement containing the declaration is entered and is freed when that compound statement is exited.
The third important kind of memory allocation which is Dynamic Memory Allocation is not supported by C variables but is available through GNU C Library functions.
Now let's talk about Dynamic Memory allocation and its functions.
What is Dynamic Memory Allocation?
Dynamic memory allocation is the process of allocating or de-allocating a block of memory during the run time of a program. we can say dynamic memory allocation is the manual allocation and freeing up space depending on how your program needs.
There are four functions used in Dynamic memory allocation which are stated below
- Memory allocation or malloc() is a function that is used to dynamically allocate a block of memory with a specified size. This function returns the Null pointer pointing to a memory address, The pointer returns type void.
syntax
ptr = (cast_type*)malloc(byte_type);
example:
ptr = (int*)malloc(500* (sizeof(int));
The byte of int is 4 bytes, this sentence above will allocate 2000 bytes of memory
The pointer ptr holds the address of the first byte in the allocated memory.
More example:
#include <stdlib.h>
#include <stdio.h>
int main()
{
//declaring pointer and variables
int* ptr;
int x, i;
//the number of element
//of the array
printf("insert a number: ");
scanf("%d", &x);
// using malloc() to allocate
// memory
ptr = (int*)malloc(x * sizeof(int));
//checking if malloc() allocated
//the memory or not
if (ptr == NULL)
{
//memory did not allocate
// successful
printf("Error\n");
exit(0);
}
else
{
//memory allocated
// successful
printf("successful\n");
for (i = 0; i < x; i++)
ptr[i] = i + 1;
//printing the element
// of array
printf("elements array are: ");
for (i = 0; i < x; i++)
printf("%d, ", ptr[i]);
}
return (0);
}
Output:
insert a number: 6
successful
elements of array are : 1, 2, 3, 4, 5, 6,
- Contiguous Allocation or calloc() is a function that is used to dynamically allocate a specified number of blocks of memory to the specified type. calloc function is similar to the malloc function but the difference is that
calloc initializes each block with a default value of 0.
calloc has two parameters as compared malloc function.
Syntax:
pointer = (cast_type*)calloc(x, size);
x is the number of elements while the size is the size of the element.
Example:
pointer = (int*) calloc(5 , sizeof(int) )
This allocates
5
bytes of calloc space of memory to each element with the size of the int.
More example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
//declaring pointer and variables
int *p, num, i;
//number of elements
num = 6;
printf("insert number:%d\n ", num);
// Using calloc() to dynamically
//allocate memory
p = (int*)calloc(num, sizeof(int));
//checking if the allocation
//was successful
if (p == NULL)
{
exit(0); // exit program
}
//get element
printf("elements of array are: ");
for (i = 0; i < num; i++)
{
p[i] = i + 1;
printf("%d, ", p[i]);
}
return (0);
}
Output:
insert number: 6
elements of array are: 1, 2, 3, 4, 5, 6,
Re-allocation or realloc() is a function in c programming that is used to dynamically change the memory allocation of a memory that has been formerly allocated. re-allocation of memory maintains the already present value and new blocks will be initialized with the default garbage value.
Syntax
pointer = realloc(pointer, new_size);
pointer is reallocated with a new size.
Example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
//declaring pointer and variables
int *p, i, num = 0;
//using malloc() to allocate memory
p = malloc(200);
// checking if memmory was allocated successfull
if (p == NULL)
{
printf("Error\n");
exit(0); //exit program
}
// using realloc() to re-allocated memory
p = realloc(p, 400);
//checking if memory was re-allocated successfull
if (p != NULL)
{
printf("successful");
}
return (0);
}
Output:
successful
De-allocate or Free() is a function in c language that is used to de-allocate or free up memory space allocated by functions like malloc() and calloc(). it takes one argument or parameter.
Syntax
void free(void *ptr);
Example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
//declaring pointer and varibles
int *p, num = 0;
//using calloc to allocate memory
p =(int*)calloc(num, sizeof(int));
//checking if the allocation was successful
if (p == NULL)
{
printf("Error\n");
exit(0); //exit program
}
//free up memory
free(p);
printf("memory free successful");
return (0);
}
Output:
memory free successful
Conclusion
Understanding the concept of Dynamic memory allocation and knowing how memory space is allocated is a benefit and best interest to a programmer.
Subscribe to my newsletter
Read articles from sharon Edeh directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
sharon Edeh
sharon Edeh
My name is Sharon Edeh. I specialize in web development and technical writing. My professional focus lies in problem-solving, and I am deeply passionate about simplifying intricate issues into their most accessible forms.