C Programming Basics

In C, which of the following is the most appropriate reason it is recommended to write p = NULL; right after free(p);?

  1. AUnless NULL is assigned, the released region does not become available again, causing a memory leak
  2. Bp keeps pointing to the released region, so this prevents double frees and use after free and makes them easier to find
  3. Cfree sets p to NULL automatically, but writing the same value again is a safety check
Show answer and explanation

Answer: B. p keeps pointing to the released region, so this prevents double frees and use after free and makes them easier to find

free(p) releases the region p pointed to, but the value (address) of the variable p remains unchanged. Reading or writing *p afterwards is use after free, and calling free(p) again is a double free; both are undefined behavior and can corrupt the heap's bookkeeping so that a failure appears somewhere far away. If p is set to NULL, the double free is harmless because free(NULL) is defined to do nothing, and a NULL check before use also reveals the mistake. Other pointer variables that point to the same region still need separate care.

  • A. The region is released when free is called. Assigning NULL has nothing to do with whether it is released.
  • B. Correct. It prevents use after free and double frees and makes them easier to find.
  • C. free does not change the value of p. After the call, p still points to the released address.
Practice this topic Back to topic

Books on C Programming Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More C Programming Basics questions

  1. The 8-character string "ABCDEFGH" was passed to the function save above. Which of the following is what happens?
  2. In C, which of the following describes what happens when a null pointer is dereferenced (*p is read while p is NULL)?
  3. Assume a typical environment where char is 1 byte and int is 4 bytes, with int placed at addresses that are multiples of 4. Which of the following is the output when the code above is executed?
  4. uint32_t and uint8_t are 32-bit and 8-bit unsigned integer types, and the environment is little-endian. Which of the following is the output when the code above is executed?
  5. Which of the following is the output when the code above, which stores 9 in a 3-bit bit-field, is executed?