T2402100330034 DynamicMemoryAllocation
T2402100330034 DynamicMemoryAllocation
int main() {
int* ptr = (int*) malloc(sizeof(int)); //Allocate the memory for an integer
if (ptr == NULL) {
printf("Memory allocation failed.\n"); //To check if memory allocation was failed or not
return -1;
}
*ptr = 10; //Assign a value to the allocated memory
printf("Value at ptr: %d\n", *ptr);
int main() {
int* ptr = malloc(2 * sizeof(int));
ptr[0] = 10;
ptr[1] = 20;
free(ptr);
return 0;
}
Code Example 4: Freeing Dynamically Allocated Memo
How to free dynamically allocated memory using free() function.
#include <stdio.h>
#include <stdlib.h>
int main() {
int* ptr = malloc(sizeof(int));
*ptr = 10;
printf("Allocated memory: %d\n", *ptr);
free(ptr);
return 0;
}
Code Example 5: Dynamically Allocated Memory
How to allocate memory dynamically using malloc(), calloc(), realloc() and free(
#include <stdio.h>
#include <stdlib.h>
int main() {
int* ptr1 = (int*)malloc(sizeof(int));
*ptr1 = 10;
printf("Memory allocated using malloc: %d\n", *ptr1);
free(ptr1);
return 0;
}
Conclusion
Dynamic memory allocation in C offers flexibility and efficiency but
requires careful management. Understanding the advantages,
disadvantages, and proper usage of dynamic memory allocation
functions is essential for writing robust and secure C programs.
Thank you