Govt. Exams
Entrance Exams
Stack allocation (option A) will cause stack overflow. Dynamic allocation on heap is required for large data.
Dangling pointer points to memory that has been freed. Accessing it causes undefined behavior.
int *p = malloc(sizeof(int));
int *q = p;
free(p);
q[0] = 5; // What is the result?
Both p and q point to freed memory. Writing to q after free(p) is undefined behavior.
char *str = malloc(5);
strcpy(str, "Hello World");
Buffer overflow occurs (11 chars into 5 bytes), and memory is never freed, causing a leak.
void func() {
int *ptr;
ptr = malloc(sizeof(int) * 5);
func2(ptr);
free(ptr);
}
void func2(int *p) {
free(p);
}
Memory is freed in func2(), then again in func(), causing double free error.
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.