ProgrammingHard
A pointer p is freed with free(p) and then set to NULL. Why is this safer than leaving it dangling?
- A. It frees the block a second time, which reclaims more memory
- B. A later free(p) or a read through p becomes a defined no-op or an explicit NULL check, instead of undefined behaviour
- C. It moves the block to the stack
- D. It prevents the compiler from optimising the code
Correct answer: B. A later free(p) or a read through p becomes a defined no-op or an explicit NULL check, instead of undefined behaviour
Setting the pointer to NULL turns later accidental uses into safe checks. A second free of the same pointer would still be undefined.
More C Programming questions
- Which code creates a flexible structure holding n ints after a header, with a single allocation and correct size?
- A tail-insertion function takes a pointer to the head pointer, so it can work on an empty list. Which loop finds the link to change?
- A queue with head and tail pointers is emptied by dequeuing its only node. What must the dequeue do to keep the queue correct?
- A recursive function removes all nodes equal to x from a singly linked list and returns the new head. Which return statement is the right…
- A program creates an array of 10^6 pointers and then one malloc block per pointer, with 10^6 frees at the end. What is the total number of…
- What is the effect of realloc(p, 0) when p came from malloc, in the C standard's terms?