Govt Exams
Each node should be allocated individually with malloc() to allow dynamic growth and efficient memory usage.
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(10);
p = realloc(p, 20);
realloc() extends the existing allocation, preserving original data, and may return the same or different address.
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.
Dynamic memory allows flexible sizing at runtime, which static arrays cannot provide.
According to C standard, free(NULL) is safe and does nothing.
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.
calloc() takes two parameters (count, size) and initializes memory to 0, while malloc() takes one parameter and leaves memory uninitialized.