Learning Sections show
Dynamic Memory Allocation in C
Example
#include<stdio.h> // Include the standard input-output library
#include<stdlib.h> // Include the standard library for malloc and free
int main() {
// Pointer for dynamically allocated memory
int *ptr;
// Allocate memory for 5 integers
ptr = (int *) malloc(5 * sizeof(int));
// Check if the memory has been successfully allocated
if (ptr == NULL) {
printf("Memory not allocated.\n");
return 1;
}
// Memory has been successfully allocated, initialize and use it
for (int i = 0; i < 5; i++) {
ptr[i] = i + 1;
}
// Print the allocated memory values
for (int i = 0; i < 5; i++) {
printf("%d\n", ptr[i]);
}
// Free the dynamically allocated memory
free(ptr);
return 0;
}
Explanation:
Dynamic memory allocation in C allows you to allocate memory during runtime using functions such as malloc, calloc, realloc, and free. This provides flexibility when dealing with data whose size may not be known at compile time.
In this example:
#include<stdio.h>and#include<stdlib.h>: Include the standard input-output and standard library headers necessary for memory allocation functions.int *ptr;: Declares a pointer to an integer which will point to the dynamically allocated memory.ptr = (int *)malloc(5 * sizeof(int));: Allocates memory for 5 integers and assigns the address of the allocated memory toptr. If the allocation fails,mallocreturnsNULL.if (ptr == NULL): Checks if the memory allocation was successful. If not, an error message is printed and the program exits.for (int i = 0; i < 5; i++) { ptr[i] = i + 1; }: Initializes the allocated memory with values 1 to 5.for (int i = 0; i < 5; i++) { printf("%d\n", ptr[i]); }: Prints the values stored in the dynamically allocated memory.free(ptr);: Frees the dynamically allocated memory to avoid memory leaks.return 0;: Ends the main function and returns 0 to the operating system, indicating that the program ended successfully.
In summary, dynamic memory allocation in C is crucial for managing memory efficiently, especially when the size of the data is not known at compile time.