C Memory Management
This chapter explains dynamic memory management in C. C provides several functions for memory allocation and management. These functions can be found in the
In C, memory is managed through pointer variables. A pointer is a variable that stores a memory address, which can point to a variable of any data type, including integers, floats, characters, and arrays. C provides functions and operators that allow programmers to manipulate memory, including allocating, freeing, moving, and copying it.
| No. | Functions and Description |
|---|---|
| 1 | *void calloc(int num, int size); |
| dynamically allocates num contiguous spaces of length size in memory and initializes every byte to 0. The result is a memory space of num*size bytes, with every byte set to 0. | |
| 2 | **void free(void *address); ** |
| This function frees the memory block pointed to by address, releasing dynamically allocated memory space. | |
| 3 | **void *malloc(int num); ** |
| allocates a block of memory of the specified size on the heap to store data. This memory is not initialized after allocation, so its values are unknown. | |
| 4 | **void *realloc(void *address, int newsize); ** |
| This function reallocates memory, extending it to newsize. |
**Note:** The void * type represents a pointer to an unspecified type. C and C++ allow a void * to be cast to any other pointer type.
Dynamic Memory Allocation
When programming, if you know the size of an array in advance, defining it is easy. For example, an array storing names holds at most 100 characters, so you can define it as follows:
char name[100];
However, if you do not know the length of the text to be stored in advance, for example, you want to store a detailed description of a topic, you need to define a pointer to characters with an unspecified memory size, and then allocate memory later as needed, as follows:
Example
#include
<
stdio.h
#include
<
stdlib.h
#include
<
string.h
int
main
(
)
{
char
name
[
100
];
char
description
;
strcpy
(
name
,
"
Zara Ali
"
)
;
/*
Dynamic Memory Allocation
*/
description
=
(
char
)
malloc
(
200
sizeof
(
char
)
)
;
if
(
description
==
NULL
)
{
fprintf
(
stderr
,
"
Error - unable to allocate required memory
\
n
"
)
;
}
else
{
strcpy
(
description
,
"
Zara ali a DPS student in class 10th
"
)
;
}
printf
(
"
Name = %s
\
n
"
,
name
)
;
printf
(
"
Description: %s
\
n
"
,
description
)
;
}
When the code above is compiled and executed, it produces the following result:
Name = Zara Ali
Description: Zara ali a DPS student in class 10th
The above program can also be written using calloc() , simply replacing malloc with calloc, as follows:
calloc(200, sizeof(char));
When allocating memory dynamically, you have full control and can pass any size value. Arrays with a predefined size, once defined, cannot be resized.
Resizing and freeing memory
When the program exits, the operating system automatically frees all memory allocated to it, but it is recommended that you call the function whenever memory is no longer needed free() to free it.
Alternatively, you can call the function realloc() to increase or decrease the size of an allocated memory block. Let's look at the above example again using realloc() and free():
Example
#include
<
stdio.h
#include
<
stdlib.h
#include
<
string.h
int
main
(
)
{
char
name
[
100
];
char
description
;
strcpy
(
name
,
"
Zara Ali
"
)
;
/*
Dynamic Memory Allocation
*/
description
=
(
char
)
malloc
(
30
sizeof
(
char
)
)
;
if
(
description
==
NULL
)
{
fprintf
(
stderr
,
"
Error - unable to allocate required memory
\
n
"
)
;
}
else
{
strcpy
(
description
,
"
Zara ali a DPS student.
"
)
;
}
/*
Suppose you want to store a larger description
*/
description
=
(
char
)
realloc
(
description
,
100
sizeof
(
char
)
)
;
if
(
description
==
NULL
)
{
fprintf
(
stderr
,
"
Error - unable to allocate required memory
\
n
"
)
;
}
else
{
strcat
(
description
,
"
She is in class 10th
"
)
;
}
printf
(
"
Name = %s
\
n
"
,
name
)
;
printf
(
"
Description: %s
\
n
"
,
description
)
;
/*
Freeing memory with the free() function
*/
free
(
description
)
;
}
When the code above is compiled and executed, it produces the following result:
Name = Zara Ali
Description: Zara ali a DPS student.She is in class 10th
You can try not reallocating extra memory; the strcat() function will generate an error because there is not enough memory available to store description.
Commonly used memory management functions and operators in C
-
malloc() function: used to dynamically allocate memory. It takes one argument, the size of memory to allocate (in bytes), and returns a pointer to the allocated memory.
-
free() function: used to free previously allocated memory. It takes a pointer to the memory to be freed as its argument and marks that memory as unused.
-
calloc() function: used to dynamically allocate memory and initialize it to zero. It takes two arguments, the number of memory blocks to allocate and the size of each block (in bytes), and returns a pointer to the allocated memory.
-
realloc() function: used to reallocate memory. It takes two arguments, a previously allocated pointer and a new memory size, and tries to resize the previously allocated block. If successful, it returns a pointer to the reallocated memory; otherwise, it returns a null pointer.
-
sizeof operator: used to obtain the size of a data type or variable (in bytes).
-
Pointer operators: used to obtain the memory address pointed to by a pointer or the value of the variable it points to.
-
& operator: used to obtain the memory address of a variable.
-
* operator: used to obtain the value of the variable pointed to by a pointer.
-
-> operator: used for a pointer to access a structure member, with the syntax pointer->member, equivalent to (*pointer).member.
-
memcpy() function: used to copy data from a source memory area to a destination memory area. It takes three arguments, a pointer to the destination area, a pointer to the source area, and the size of data to copy (in bytes).
-
memmove() function: similar to memcpy(), but it can handle overlapping memory areas. It takes three arguments, a pointer to the destination area, a pointer to the source area, and the size of data to copy (in bytes).