ProgrammingModerate
A program calls free(p) and then reads p->v in the next line. What is the correct description?
- A. It prints the old value, because free only marks the memory as unused
- B. This is undefined behaviour, because p refers to memory that has been freed
- C. It is defined if p is not NULL
- D. It is an error at compile time
Correct answer: B. This is undefined behaviour, because p refers to memory that has been freed
Reading an object after free is undefined, even if the old value often still appears. Compilers do not necessarily report it.
More C Programming questions
- A hash chain delete on a singly linked bucket list is written with a pointer-to-pointer. Which description is the advantage?
- Building a list from n values by inserting each new node at the head is O(1) per insert. What is the order of the values when read from…
- Which C statement is correct for a node with an int field v and a next pointer, allocated and initialised to v = 7 with no next node?
- A doubly linked list stores prev pointers. How many pointer fields must change to insert a new node between two adjacent nodes A and B?
- A singly linked list of N = 10^6 nodes must answer 10^6 queries for the value at position k. Which approach is correct and fast enough?
- A function frees an entire list and then sets head = NULL. Why is setting head to NULL useful?