0% found this document useful (0 votes)
11 views

Dynamic Memory Allocation

1. The document discusses dynamic memory allocation in C and C++. It allocates and deallocates memory during program runtime as opposed to static allocation at compile time. 2. In C, functions like malloc(), calloc(), and realloc() allocate memory and return pointers. The memory is uninitialized so it must be initialized manually. Free() must be used to deallocate memory to avoid leaks. 3. In C++, new is used for allocation and delete for deallocation. Smart pointers like unique_ptr can automatically deallocate memory, avoiding leaks. C++ makes memory management safer and more convenient compared to C.

Uploaded by

devil hunted
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Dynamic Memory Allocation

1. The document discusses dynamic memory allocation in C and C++. It allocates and deallocates memory during program runtime as opposed to static allocation at compile time. 2. In C, functions like malloc(), calloc(), and realloc() allocate memory and return pointers. The memory is uninitialized so it must be initialized manually. Free() must be used to deallocate memory to avoid leaks. 3. In C++, new is used for allocation and delete for deallocation. Smart pointers like unique_ptr can automatically deallocate memory, avoiding leaks. C++ makes memory management safer and more convenient compared to C.

Uploaded by

devil hunted
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Name:Rakshita K

USN:2VX21CB018

DYNAMIC MEMORY ALLOCATION


Dynamic memory allocation is a programming concept that involves allocating and deallocating
memory during the runtime of a program. It allows programs to request memory from the operating system as
needed and manage memory usage efficiently. This is in contrast to static memory allocation, where memory is
allocated at compile time and is fixed.

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);

// Allocate memory for an integer array of the specified size


int* intArray = (int*)malloc(size * sizeof(int));

if (intArray == NULL) {
printf("Memory allocation failed\n");
return 1; // Exit with an error code
}

// Initialize the array with some values


for (int i = 0; i < size; i++) {
intArray[i] = i * 10;
}

// Display the contents of the array


printf("Array contents:\n");
for (int i = 0; i < size; i++) {
printf("%d ", intArray[i]);
}
printf("\n");

// Deallocate the allocated memory


free(intArray);

return 0; // Exit successfully


}

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
}

// Display the contents of the array (should be all zeros)


printf("Array contents:\n");
for (int i = 0; i < size; i++) {
printf("%d ", intArray[i]);
}
printf("\n");

// Deallocate the allocated memory


free(intArray);

return 0; // Exit successfully


}

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);

// Allocate memory for an integer array of the initial size


int* intArray = (int*)malloc(size * sizeof(int));

if (intArray == NULL) {
printf("Memory allocation failed\n");
return 1; // Exit with an error code
}

// Initialize the array with some values


for (int i = 0; i < size; i++) {
intArray[i] = i * 10;
}

// Display the contents of the initial array


printf("Initial array contents:\n");
for (int i = 0; i < size; i++) {
printf("%d ", intArray[i]);
}
printf("\n");
// Ask the user to enter the new size for the array
int newSize;
printf("Enter the new size of the integer array: ");
scanf("%d", &newSize);

// 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
}

// Update the pointer after successful reallocation


intArray = resizedArray;

// Display the contents of the resized array


printf("Resized array contents:\n");
for (int i = 0; i < newSize; i++) {
printf("%d ", intArray[i]);
}
printf("\n");

// Deallocate the allocated memory


free(intArray);

return 0; // Exit successfully


}

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);

// Allocate memory for an integer array of the specified size


int* intArray = (int*)malloc(size * sizeof(int));

if (intArray == NULL) {
printf("Memory allocation failed\n");
return 1; // Exit with an error code
}

// Initialize the array with some values


for (int i = 0; i < size; i++) {
intArray[i] = i * 10;
}

// Display the contents of the array


printf("Array contents before deallocation:\n");
for (int i = 0; i < size; i++) {
printf("%d ", intArray[i]);
}
printf("\n");
// Deallocate the allocated memory
free(intArray);

// Display a message to indicate memory deallocation


printf("Memory deallocated\n");

return 0; // Exit successfully


}

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
}

// Display the address of the allocated memory


printf("Aligned memory address: %p\n", (void*)alignedArray);

// Deallocate the allocated memory


free(alignedArray);

return 0; // Exit successfully


}
Dynamic Memory Allocation in C and C++

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.

C Dynamic Memory Allocation:

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.

C++ Dynamic Memory Allocation:

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.

You might also like