Govt Exams
All memory allocation and deallocation functions are declared in <stdlib.h>.
sizeof(int) * 10 = 4 * 10 = 40 bytes on a 32-bit system.
int *p = malloc(5 * sizeof(int));
p = realloc(p, 10 * sizeof(int));
realloc() resizes the memory block while preserving existing data. If expansion in-place fails, it allocates new block and copies data.
For true 2D dynamic array, allocate pointer array first, then allocate each row. Option C is 1D linear allocation.
void func() {
int *p = malloc(sizeof(int));
*p = 5;
}
int main() {
func();
// p is not accessible here
return 0;
}
The pointer p is local to func(). Memory is allocated but never freed, causing a memory leak.
Dynamic memory persists until free() is called, unlike automatic variables which are freed at function end.
Dereferencing a NULL pointer causes undefined behavior, typically resulting in segmentation fault or program crash.
int *p = malloc(sizeof(int) * 3);
p[0] = 1; p[1] = 2; p[2] = 3;
printf("%d", *(p+2));
*(p+2) is equivalent to p[2], which contains 3. Pointer arithmetic works with dynamic arrays.
char *str = malloc(5);
strcpy(str, "Hello");
How many bytes should malloc allocate for safety?
String "Hello" has 5 characters plus 1 null terminator (\0), requiring 6 bytes total.
Double free error occurs when free() is called on the same memory block twice, causing undefined behavior and program crash.