Govt Exams
int *p = calloc(3, sizeof(int));
printf("%d %d %d", p[0], p[1], p[2]);
calloc() initializes all allocated bytes to 0, so all integers are 0.
void func() {
int *p = malloc(100);
if(condition) return;
free(p);
}
When condition is true, the function returns without calling free(), causing a memory leak.
int *p = (int*)malloc(sizeof(int));
Typecasting malloc() is optional in C but improves readability. It's mandatory in C++.
Option B uses dynamic allocation (2D array), Option C uses static allocation. Both are valid but for different scenarios.
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.
Dynamic array allocation requires pointer and malloc() with proper size calculation. VLAs are not standard C.
realloc() resizes a previously allocated memory block. It can increase or decrease the size and preserves existing data.
Accessing freed memory results in undefined behavior and is a critical bug. The memory may be reallocated for other purposes.