G25 Answer


#include <stdio.h>
typedef struct
{
  int x, y;
} Point;

void printPoint( Point *p )
{
  printf("(%d, %d) ", p->x, p->y );
}

typedef struct
{
  int red, green, blue;
} Color;

void printColor( Color *c )
{
  printf("%3d red, %3d grn, %3d blu", c->red, c->green, c->blue );
}

typedef struct
{
  Point *p0, *p1, *p2;
  Color *color;
} TriangleMod;

void printTriangleMod( TriangleMod *t )
{
  printf("Points: ");
  printPoint( t->p0 ); printPoint( t->p1 ); printPoint( t->p2 );
  printf("\nColor: ");
  printColor( t->color );
  printf("\n");
}

int main()
{
  TriangleMod *trimod;

  trimod = (TriangleMod *)malloc( sizeof( TriangleMod ) );
  trimod->p0 = (Point *)malloc( sizeof( Point ) );
  trimod->p1 = (Point *)malloc( sizeof( Point ) );
  trimod->p2 = (Point *)malloc( sizeof( Point ) );
  trimod->color = (Color *)malloc( sizeof( Color ) );

  /* Initialize trimod here */
  trimod->p0->x = 50;
  trimod->p0->y = 150;
  trimod->p1->x = 75;
  trimod->p1->y = 80;
  trimod->p2->x = 0;
  trimod->p2->y = 0;
  trimod->color->red = 120;
  trimod->color->green = 240;
  trimod->color->blue = 50;

  /* Print out trimod here */
  printTriangleMod( trimod );

  /* Free dynamic memory */
  free( trimod->color);
  free( trimod->p0);
  free( trimod->p1);
  free( trimod->p2);
  free( trimod );

  system( "pause" );
}

Comments: When memory is freed, the memory pointed at by trimod must be freed last. The following is WRONG:

  free( trimod );
  free( trimod->color);
  free( trimod->p0);
  free( trimod->p1);
  free( trimod->p2);

In the mistaken code, after trimod has been freed, the operating system might immediately allocate it for some other purpose, so the next statement

  free( trimod->color);

might grab data from memory that has been changed. Remember that free() is (ultimately) an operating system service, and that tens of thousands of machine instructions from the OS and other programs might execute before control returns to your program.

The mistaken code will almost always execute without anything bad happening. But in a real production envinronment, that code leaves open the possibility of a very nasty bug that will be very hard to track down.