Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

// Identify as many bugs and assumptions as you can in the following code. // NO

ID: 660908 • Letter: #

Question

// 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++;
   }
}

Explanation / Answer

Answer:

One major Algorithmic assumptions is:

Pointers are both aligned on integer boundaries so the integer part of the copy can work.
Generally, he memory regions do not overlap.


Two Portability assumptions are:

1. sizeof(int) == 4.

Pointers can be misaligned without incurring performance cost.They lead to segmentation violation on some machines (SPARC, PowerPC), extra memory reads on others.

2. nBytes >= 0.
There was a user-level command uac (unaligned access control) to manipulate how the system handled unaligned memory accesses.

Bugs are:

1. Syntax error on line
for (int i=0 ; i <= numRemaining; i++);
2. Missing a semi colon after the loop
for (int i=0; i < numWords; i++)
3. i <= numRemaining should be i < numRemaining.
Casting away of const was not necessary.