Which of the following best explains why dynamic memory allocation is needed in C programming?
Think about when the program needs memory but does not know how much it will need before running.
Dynamic memory allocation allows a program to request memory while it is running, which is useful when the amount of memory needed cannot be determined before the program starts.
What is the output of the following C code?
#include <stdio.h> #include <stdlib.h> int main() { int *ptr = (int *)malloc(3 * sizeof(int)); if (ptr == NULL) { printf("Memory allocation failed\n"); return 1; } ptr[0] = 10; ptr[1] = 20; ptr[2] = 30; printf("%d %d %d\n", ptr[0], ptr[1], ptr[2]); free(ptr); return 0; }
Check if memory allocation was successful and values assigned before printing.
The program allocates memory for 3 integers, assigns values, and prints them. Since allocation succeeds, it prints '10 20 30'.
What will be the output of this C program if malloc fails to allocate memory?
#include <stdio.h> #include <stdlib.h> int main() { int *ptr = (int *)malloc((size_t)1000000000000 * sizeof(int)); if (ptr == NULL) { printf("Allocation failed\n"); } else { printf("Allocation succeeded\n"); free(ptr); } return 0; }
Consider what happens when malloc cannot find enough memory.
If malloc cannot allocate the requested memory, it returns NULL, so the program prints 'Allocation failed'.
Why is dynamic memory allocation preferred over static allocation for large or variable-sized data in C?
Think about when the program size or data size is not known before running.
Static memory is allocated at compile time and cannot change size, so dynamic memory is used for large or variable data sizes during runtime.
What is the value of ptr after calling free(ptr); in this program?
#include <stdio.h> #include <stdlib.h> int main() { int *ptr = malloc(sizeof(int)); *ptr = 42; free(ptr); printf("%p\n", (void *)ptr); return 0; }
Does free() change the pointer variable itself?
Calling free() releases the memory but does not change the pointer value. The pointer still holds the address but it is now a dangling pointer.