Govt Exams
struct Node { int data; char name[20]; };
Must allocate n * sizeof(struct Node) bytes to hold all n structures.
Dynamic allocation allocates memory on heap based on runtime input, preventing fixed-size limitations and stack overflow.
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.
realloc() finds new space if needed, copies data, deallocates old block, and returns new pointer.
int *p = (int*)calloc(3, sizeof(int));
printf("%d %d %d", p[0], p[1], p[2]);
calloc() initializes all allocated memory to zero, so all elements will be 0.
Original malloc(10) pointer is lost before freeing. The 10 bytes are now inaccessible - a memory leak.
calloc(num, size) allocates num * size = 10 * 4 = 40 bytes total.
After free(), accessing the pointer causes undefined behavior as memory is returned to the heap and may be reused.
int **arr = (int**)malloc(m * sizeof(int*));
what does the first malloc() allocate?
First malloc allocates an array of m pointers. Each pointer must be individually allocated in a loop for actual row data.
Double-free causes undefined behavior (segmentation fault). free() doesn't set pointer to NULL; programmer must do it explicitly.