CS360 Midterm -- March 14, 2002. Answer/Grading for Question 3


Answer

Ok -- now what you need to do is take the return value of malloc(), XOR it with 0x3579acd3, and store it four bytes before the return value.

Here is that code:

void *malloc(int size)
{
  void *retval;

  YOUR DECLARATIONS GO HERE

  int *ckptr;
  int cksum;

  /* Code for malloc is here */

  YOUR CODE FOR MALLOC GOES HERE

  cksum = ((int) retval) ^ 0x3579acd3;
  ckptr = (int *) retval;
  ckptr[-1] = cksum;

  return *retval;
}
Now, in free, you calculate the checksum from the pointer given to you and check four bytes behind it to see if it equals the checksum stored there. If so, you're fine. If not, dump core:
void *free(void *ptr)
{

  YOUR DECLARATIONS AND CODE FOR FREE GO HERE 

  int *ckptr;
  int cksum;

  cksum = ((int) ptr) ^ 0x3579acd3;
  ckptr = (int *) ptr;
  if (ckptr[-1] != cksum) {
    ckptr = (int *) NULL;      /* Dump core */
    *ckptr = 0;
  }

  /* The rest of free's code is here */
}

Grading - 8 points

Breakdown is as follows: You needed to actually dump core, not exit with -1, or print out ``core dump.''