#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

// vector of int pointers
typedef struct vector {
  int n, size;
  int **x;
} Vector;

// make a new vector object
Vector *make_vector (int size)
{
  // allocate the vector object
  Vector *vector = (Vector *) malloc (sizeof (Vector));
  assert (vector != NULL);

  // allocate space for the data
  vector->x = (int **) malloc (size * sizeof (int *));
  assert (vector->x != NULL);

  // n is the number of elements in the vector
  vector->n = 0;

  // size is the current allocated size
  vector->size = size;
  return vector;
}

// remove all elements from the vector
void clear_vector (Vector *vector) {
  vector->n = 0;
}

// deallocate the vector and its data
void free_vector (Vector *vector)
{
  free (vector->x);
  free (vector);
}

// resize the vector by reallocating space for the data
void resize_vector (Vector *vector, int size)
{
  printf ("resizing vector, new size = %d\n", size);
  vector->x = (int **) realloc (vector->x, size * sizeof (int *));
  assert (vector->x != NULL);
  vector->size = size;
}

// add a new element to the vector, doubling the size if necessary
void add_to_vector (Vector *vector, int *element)
{
  if (vector->n >= vector->size) {
    resize_vector (vector, vector->size * 2);
  }
  vector->x[vector->n] = element;
  vector->n++;
}

// allocate the requested space and check the result
void *mymalloc (int size) {
  void *result = malloc (size);

  // assert is a quick and dirty way to do error-checking
  assert (result != NULL);
  return result;
}

// print the contents of a DateTime object
void thrash(void)
{
  Vector *v = make_vector(1024);
  int *chunk;

  // simulate a process with a memory leak by allocating
  // chunks of memory forever
  while (1) {
    chunk = (int *) mymalloc (1024 * sizeof(int));
    printf ("0x%x\n", chunk);
    add_to_vector(v, chunk);
  }
}

int main()
{
  thrash();
  return 0;
}

