Interview Question

Senior Software Engineer Interview Sunnyvale, CA

Write a function to copy the NULL terminated string? The

  source & destination can be any where with overlap possible. The end result should be that the destination should have string properly without getting corrupted.

Interview Answer

2 Answers


Copy from end to begin so that destination will has the string of source.

Viswesn on Aug 3, 2012

That doesn't work because if src > dst, there is an overlap and strlen( src ) > ( src - dst ) then a backwards copy will corrupt the result.

So you should check if src > dst and if so do a regular forward copy otherwise check if src < dst and if so do a backward copy while letting the condition of src == dst just fall through.

For the second test of src < dst you could also check if src + strlen( src ) <= dst and if so just do a forward copy reserving the backward copy for src + strlen( src ) > dst. The catch is that doing that actually adds an extra conditional check and an extra call to the forward function in the code - slightly increasing the code size and execution time.

Michael on Apr 7, 2014

Add Answers or Comments

To comment on this, Sign In or Sign Up.