Computer Networks (CSC-364 2000S)


Class 09: Memory Management

Back to Pointers. On to Data-Link Basics.

Held Friday, February 11, 2000

Overview

Today, we conclude our study of C by visiting some further issues of memory management.

Notes

Contents

Summary


Pointers and Arrays

Allocation and Deallocation

Dangers

Pointer Lab

Allocation with arrays

Consider the following program:

#include <stdio.h>

int *stuff;

/* "Allocate" space for stuff. */
void setupStuff()
{
  int junk[10];
  int i;
  stuff = junk;
  for (i = 0; i < 10; i++)
    stuff[i] = i;
} /* setupStuff() */

/* Print some values */
void printVals()
{
  int i,j,k;
  j = 100;
  k = 200;
  for (i = 0; i < 10; i++)
    printf("stuff[%d]: %d\n", i, stuff[i]);
  printf("i: %d\n", i);
  printf("j: %d\n", j);
  printf("k: %d\n", k);
} /* printVals() */

main()
{  
  setupStuff();
  printVals();
} /* main() */

Aliasing

Consider the following program:

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

#define ENTRIES 5

main()
{
  int i;
  int *A;
  int *B;
  int *C;
  A = (int *) malloc(ENTRIES * sizeof(int));
  B = A;
  C = (int *) malloc(ENTRIES * sizeof(int));
  for (i = 0; i < ENTRIES; i++) {
    A[i] = i;
    C[i] = i;
  }
  for (i = 0; i < ENTRIES; i++)
    printf("B[%d]: %d; ", i, B[i]);
  printf("\n");
  for (i = 0; i < ENTRIES; i++)
    printf("C[%d]: %d; ", i, C[i]);
  printf("\n");
  free(A);
  A = malloc((ENTRIES-1) * sizeof(int));
  for (i = 0; i < ENTRIES-1; i++)
    A[i] = 9*i;
  for (i = 0; i < ENTRIES; i++) 
    printf("B[%d]: %d; ", i, B[i]);
  printf("\n");
  for (i = 0; i < ENTRIES; i++) 
    printf("C[%d]: %d; ", i, C[i]);
  printf("\n");
} 

History

Thursday, 20 January 2000

Friday, 11 February 2000

Back to Pointers. On to Data-Link Basics.


Disclaimer Often, these pages were created "on the fly" with little, if any, proofreading. Any or all of the information on the pages may be incorrect. Please contact me if you notice errors.

This page may be found at http://www.math.grin.edu/~rebelsky/Courses/CS364/2000S/Outlines/outline.09.html

Source text last modified Mon Feb 14 12:46:58 2000.

This page generated on Mon Feb 14 12:52:15 2000 by Siteweaver. Validate this page's HTML.

Contact our webmaster at rebelsky@grinnell.edu