Link back to syllabus

Function tomfoolery

Consider this function:

void f()
{
  int magic[1];
  int a;
  char b;
  long c;
  char d;

  /* YOUR CODE HERE */

  printf("%d %c %ld %c\n", a, b, c, d);
}

Without mentioning a, b, c, or d, replace /* YOUR CODE HERE */ (and write the rest of the program), so that this function prints out 42 A 113 Z. You will have to do unsavory things like access an array outside of its bounds.

In order to do this, you will have to learn the precise memory layout of the variables a, b, c, and d. There are several ways to do this: using & and printing and using gdb are two excellent choices. It is thus expected that you do several data-collecting experiments before you are able to accurately get the output that you want.

When you get this working, call me over. Show me a drawn diagram of the memory layout of the function.

Array tomfoolery

Consider this program:

void f(int a[])
{
  /* YOUR CODE HERE */
}

int main()
{
  int nums[3][3];

  f(nums);

  for(int i = 0; i < 3; i++)
  {
    for(int j = 0; j < 3; j++)
    {
      printf("%d ", nums[i][j]);
    }
    printf("\n");
  }

  return 0;
}

This program should print

1 4 7
2 5 8
3 6 9

Fill in /* YOUR CODE HERE */ to make it so. Note that the argument to f is a one-dimensional array. This is intentional!

Stack frame tomfoolery

Now, we have this program:

void f()
{
  int arr[1];
  /* YOUR CODE HERE */
}

int main()
{
  int x;
  f();
  printf("%d\n", x);
  return 0;
}

Without printing anything in f, this program should print 1885. Do this by accessing arr outside of its range in such a way that you affect the memory for the variable x. Once again, using gdb will be helpful to figure out where everything is in memory.

Git

Follow the tutorial at https://git-scm.com/docs/gittutorial, but read the following notes first: