Govt Exams
Using dynamic adjacency lists, you allocate V list pointers and E edge nodes total, giving O(V + E) space complexity, which is optimal for sparse graphs.
while(1) { int *arr = malloc(1000000); }
This creates an infinite loop that allocates 1MB each iteration without freeing, rapidly exhausting available memory. This is a classic memory leak scenario.
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.
Calling free(NULL) is safe in C and does nothing. This is by design, allowing you to write code like free(ptr) without checking if ptr is NULL first.
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.
When malloc() cannot allocate the requested memory, it returns NULL. The programmer must check for NULL before using the pointer to avoid undefined behavior.