C Programming · Interview question

What's wrong with returning a pointer to a local variable?

A strong answer

The local lives in the function's stack frame, which is popped the moment the function returns. The returned pointer therefore points at memory that's no longer reserved for that variable, it's a dangling pointer. The next function call will reuse that stack space, overwriting the bytes. The insidious part is that it often appears to work in simple tests, because the bytes haven't been clobbered yet, so the bug is intermittent and environment-dependent. The fixes: have the caller pass in a buffer (f(char *out, size_t n), the idiomatic embedded pattern), heap-allocate and return that (caller frees), or use static storage if you accept that it's shared and not reentrant. Returning the address of a local is never correct.

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

Stack vs Heap

Where your variables actually live: automatic stack storage vs manual heap allocation, and why returning a pointer to a local is the classic firmware crash.

More Stack vs Heap questions

Browse all 472 interview questions
What's wrong with returning a pointer to a local variable? | EmbeddedPrep.io