If realloc fails, it returns NULL but leaves the original block allocated and untouched. By assigning the result straight back onto ptr, you've overwritten your only reference to the still-valid old block with NULL, instant leak, and you've also lost your data. The correct pattern uses a temporary: void *tmp = realloc(ptr, new_size); if (tmp) ptr = tmp; else { /* handle failure, ptr still valid */ }. Also worth noting: realloc may move the block to satisfy a grow request, so any other pointers into the old block become dangling after a successful realloc, you must update them too.
C Programming · Interview question
What's wrong with ptr = realloc(ptr, new_size);?
A strong answer
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
Dynamic Memory: malloc & free
Sizing memory at runtime with malloc/calloc/realloc, and the discipline of free that prevents leaks, double-frees, and use-after-free bugs.