Dynamic Memory Allocation
Dynamic Memory Allocation
USN:2VX21CB018
1. malloc( ):
• Allocates a block of memory.
• It is used to allocate memory space as per requirement.
• Function allocates memory and returns a pointer of type void * to the start of that memory block.
• If function fails it returns Null.
• This function does not initialize the memory allocated during execution, it carries garbage value.
Syntax:
ptr = (datatype *) malloc(size);
Example:
int *ptr;
ptr = (int * ) malloc ( 30 );
Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int size;
printf("Enter the size of the integer array: ");
scanf("%d", &size);
if (intArray == NULL) {
printf("Memory allocation failed\n");
return 1; // Exit with an error code
}
2.Calloc( ):
• Allocates multiple block of memory.
• It is similar to malloc( ) ,but it intializes the allocated memory to zero.
Syntax:
ptr = (datatype *) calloc (n, size) ;
Example:
Ptr = (int *) calloc (20, size of ( int )) ;
Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int size;
printf("Enter the size of the integer array: ");
scanf("%d", &size);
// Allocate memory for an integer array of the specified size and initialize with zeros
int* intArray = (int*)calloc(size, sizeof(int));
if (intArray == NULL) {
printf("Memory allocation failed\n");
return 1; // Exit with an error code
}
3. realloc( ) :
• Used to modify the size of allocated block by malloc( ) ,calloc( ) to new size.
• If allocated memory space i,e not sufficient then additional memory can be taken using realloc( ).
• Can also be used to reduce the size of already allocated memory.
sy ntax:
ptr = (datatype *) realloc (ptr, new size );
Example:
int* resizedArray = (int*)realloc(intArray, 10 * sizeof(int));
Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int size;
printf("Enter the initial size of the integer array: ");
scanf("%d", &size);
if (intArray == NULL) {
printf("Memory allocation failed\n");
return 1; // Exit with an error code
}
// Reallocate memory for the integer array with the new size
int* resizedArray = (int*)realloc(intArray, newSize * sizeof(int));
if (resizedArray == NULL) {
printf("Memory reallocation failed\n");
free(intArray); // Free the original allocated memory
return 1; // Exit with an error code
}
4. free( ) :
• Deallocate the allocated memory which was done using malloc( ), calloc( ), realloc( ) .
Syntax:
free( pointer name);
Example:
free( str);
Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int size;
printf("Enter the size of the integer array: ");
scanf("%d", &size);
if (intArray == NULL) {
printf("Memory allocation failed\n");
return 1; // Exit with an error code
}
5. aligned alloc( ):
• Allocates a block of memory with the specified alignment and size. Alignment must be a power of two,
and the returned pointer will have the specified alignment.
Syntax:
void* aligned_alloc(size_t alignment, size_t size);
Example:
int* alignedPtr = (int*)aligned_alloc(32, sizeof(int));
Program:
#include <stdio.h>
#include <stdlib.h>
int main() {
int size;
printf("Enter the size of the aligned integer array: ");
scanf("%d", &size);
size_t alignment;
printf("Enter the desired alignment (must be a power of 2): ");
scanf("%zu", &alignment);
// Allocate memory for an aligned integer array of the specified size
int* alignedArray = (int*)aligned_alloc(alignment, size * sizeof(int));
if (alignedArray == NULL) {
printf("Memory allocation failed\n");
return 1; // Exit with an error code
}
Dynamic memory allocation refers to the process of allocating and deallocating memory at runtime, as opposed
to static memory allocation, which is done at compile time. Both C and C++ provide mechanisms for dynamic
memory allocation, but C++ offers additional features to make memory management more convenient and safer.
1. Memory Allocation Functions: C provides functions like `malloc`, `calloc`, and `realloc` for allocating
memory. These functions return pointers to the allocated memory blocks.
2. Uninitialized Memory: The memory allocated using these functions is uninitialized and may contain random
values. You need to initialize it explicitly.
3. Manual Memory Management: After using the allocated memory, it's your responsibility to deallocate it
using the `free` function. Failing to do so can result in memory leaks.
4. Raw Pointers: C primarily uses raw pointers to manage dynamically allocated memory. You have to keep
track of memory ownership, deallocation, and potential memory leaks manually.
1. Memory Allocation Operators: C++ extends C's memory allocation by introducing the `new` and `delete`
operators. They allocate and deallocate memory and also call constructors and destructors for objects.
2. Automatic Initialization: Memory allocated using `new` is automatically initialized, which is especially
useful for objects and classes.
3. RAII: C++ emphasizes Resource Acquisition Is Initialization (RAII), where objects automatically manage
resources during their lifecycle. This includes memory management.
4. Smart Pointers : C++ provides smart pointer classes like `std::unique_ptr` and `std::shared_ptr` that
automatically manage memory and help prevent memory leaks. They track ownership and deallocate memory
when it's no longer needed.
5. STL Containers: C++'s Standard Template Library (STL) offers dynamic containers like vectors, lists, and
maps. These containers manage memory internally, making memory management less error-prone and more
convenient.
In summary, dynamic memory allocation is a core concept in both C and C++, allowing programs to allocate
memory at runtime. While C provides manual memory management with functions like `malloc` and `free`,
C++ builds on that foundation with memory allocation operators, RAII principles, smart pointers, and STL
containers to simplify and enhance memory management, making code more robust and manageable.