Govt Exams
Safe practice includes allocating exact size (input length + 1 for null terminator), checking for NULL, and using bounded string functions.
Double free is undefined behavior and can cause program crash or corruption. After first free(), the pointer should not be used.
Allocating without freeing causes memory leak, where allocated memory is not returned to the system, eventually exhausting heap.
2D arrays are allocated as array of pointers, where each row pointer points to a dynamically allocated array.
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.
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.
After free(), accessing the pointer causes undefined behavior as memory is returned to the heap and may be reused.