C Programming · Interview question

What are the ways a pointer can be invalid, and how do you guard against each?

A strong answer

Three classic bad states. NULL, the pointer deliberately points nowhere; dereferencing it is UB (a segfault on desktop). Guard by initializing to NULL and null-checking before deref. Wild/uninitialized, a bare int *p; holds whatever garbage was on the stack; dereferencing writes to a random address. Guard by always initializing pointers. Dangling, the pointer references memory that's been freed or has gone out of scope (returning the address of a local, or using after free); dereferencing is use-after-free. Guard by never returning addresses of locals, and setting pointers to NULL immediately after freeing. Tools: AddressSanitizer catches use-after-free and wild writes at runtime; -Wall catches some uninitialized uses.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Pointers & Addresses

A pointer is just a variable that holds an address. Master & and *, NULL, and how passing a pointer lets a function reach back and modify the caller's data.

More Pointers & Addresses questions

Browse all 472 interview questions
What are the ways a pointer can be invalid, and how do you guard against each? | EmbeddedPrep.io