This problem was given to me on previous job interview test. It is over now, but I would like to go through my mistakes and hopefully be more prepared next time!
// Identify as many bugs and assumptions as you can in the following code.
// NOTE that there is/are (at least):
// 1 major algorithmic assumption
// 2 portability issues
// 1 syntax error
// Function to copy 'nBytes' of data from src to dst.
void myMemcpy(char* dst, const char* src, int nBytes)
{
// Try to be fast and copy a word at a time instead of byte by byte
int* wordDst = (int*)dst;
int* wordSrc = (int*)src;
int numWords = nBytes >> 2;
for (int i=0; i < numWords; i++)
{
*wordDst++ = *wordSrc++;
}
int numRemaining = nBytes - (numWords << 2);
dst = (char*)wordDst;
src = (char*)wordSrc;
for (int i=0 ; i <= numRemaining; i++);
{
*dst++ = *src++;
}
}
All I found was a syntax error on line
for (int i=0 ; i <= numRemaining; i++);
Also the first for loop looks fishy.
Can you guys find any other mistakes?
srccan be changed. The following would be valid:src = (const char *) wordSrc;(from a const-correctness point-of-view at least). If you wanted to disallow this, declare src asconst char * const src. – Aaron McDaid May 29 '11 at 18:30