Govt Exams
Strings in C are null-terminated, so allocating strlen(s)+1 bytes ensures space for the null terminator. This is the standard safe approach.
In option A, after free(p), the memory is deallocated. Accessing it with p[0] = 5 is a use-after-free error, leading to undefined behavior.
If realloc() needs to relocate the memory block to a different address, all old pointers to the array become invalid. Only the returned pointer should be used.
In option A, the first malloc(100) block becomes inaccessible after p is reassigned, but it's not freed, causing a memory leak. The original 100 bytes are lost.
int *ptr = (int*)malloc(10);
ptr[11] = 5;
malloc(10) allocates 10 bytes, but accessing ptr[11] goes beyond the allocated boundary, causing a buffer overflow which leads to undefined behavior and potential segmentation fault.
Allocating a single contiguous block is more cache-efficient and requires only one malloc() call, making it better for competitive programming where memory access speed matters.
Reading input size first, then allocating exact size is optimal for memory efficiency and avoids repeated realloc() overhead.
This shows safe practice: allocation, use, freeing, and immediately setting pointer to NULL to avoid use-after-free.
Adjacency list uses dynamic allocation proportional to V+E, while matrix uses fixed V² space regardless of actual edges.
realloc() returns a new pointer (old location may move). Must use: p = realloc(p, newsize) and check for NULL.