Govt Exams
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.
int *p = (int*)malloc(5 * sizeof(int));
printf("%d", sizeof(p));
sizeof(p) returns the size of pointer itself (4 bytes on 32-bit, 8 bytes on 64-bit), not the allocated memory.
realloc() shrinks or expands memory. If new size is smaller, it reduces allocation and returns pointer to resized block.
Disciplined memory management with matching alloc/free pairs and proper error handling prevents leaks.
int *p = malloc(INT_MAX);
malloc() returns NULL if allocation fails (insufficient memory); always check the return value.
Fragmentation occurs when memory is allocated and freed irregularly, leaving unused gaps that waste space.
malloc() returns NULL (pointer value 0) on failure; always check before using the pointer.
Each node should be allocated individually with malloc() to allow dynamic growth and efficient memory usage.
int *p = malloc(10);
p = realloc(p, 20);
realloc() extends the existing allocation, preserving original data, and may return the same or different address.