CS360 Midterm -- March 14, 2002. Question 3

Suppose malloc() and free() have been implemented as described in class, where the size of an allocated chunk is kept 8 bytes before the pointer to the chunk.

Now, suppose you are given the task of putting a checksum into the remaining four bytes when you call malloc() and testing that checksum when you call free(). If the checksum does not match, free() should generate a segmentation violation. The checksum will be the pointer that malloc() returns XOR'd with 0x3579acd3. (The XOR operator in C is ^ -- the carat).

Write the relevant code at the end of malloc() and at the beginning of free(). (You are to provide the boldfaced code, not the other code. Do this on the answer sheet).

You may assume integers and pointers are all four bytes.

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

  YOUR DECLARATIONS GO HERE

  /* Code for malloc is here */

  YOUR CODE FOR MALLOC GOES HERE

  return *retval;
}

void *free(void *ptr)
{

  YOUR DECLARATIONS AND CODE FOR FREE GO HERE 

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