Wednesday Week 04


Wednesday Week 041/16

In This Lecture ...

Coming Up ...


Dynamic Memory Allocation2/16

So far, we have considered static memory allocation

Examples:

int   x;     // 4 bytes containing a 32-bit integer value
char *cp;    // 4 bytes containing address of a char
typedef struct {float x; float y;} Point;
Point p;     // 8 bytes containing two 32-bit float values
char  s[20]; // array containing space for 20 1-byte chars


... Dynamic Memory Allocation3/16

In many applications, fixed-size data is ok.

In many other applications, we need flexibility.

Examples:

char name[MAXNAME];  // how long is a name?
char line[MAXLINE];  // what's the longest line?
char words[MAXWORDS][MAXWORDLENGTH];
                     // how many words are there?
                     // how long is each word?

With fixed-size data, we need to guess sizes  ("large enough").


... Dynamic Memory Allocation4/16

Fixed-size memory allocation:

Dynamic memory allocation: But how to do this in C?


Dynamic Data Example5/16

Problem:

Example input:   6 25 -1 999 42 -16 64

How to define the vector?


... Dynamic Data Example6/16

Suggestion #1: allocate a large vector; use only part of it

#define MAXELEMS 1000

// how many elements in the vector
int numberOfElems;
scanf("%d", &numberOfElems);
assert(numberOfElems <= MAXELEMS);

// declare vector and fill from stdin
int i, vector[MAXELEMS];
for (i = 0; i < numberOfElems; i++) {
	scanf("%d", &vector[i]);
}

Works ok, unless too many numbers; usually wastes space.

assert() terminates program with standard error message if test fails.


... Dynamic Data Example7/16

Suggestion #2: use variables to give object sizes

// how many elements in the vector
int numberOfElems;
scanf("%d", &numberOfElems);

// declare vector and fill from stdin
int i, vector[numberOfElems];
for (i = 0; i < numberOfElems; i++) {
	scanf("%d", &vector[i]);
}

Produces compiler error   (compiler needs to know object sizes)


... Dynamic Data Example8/16

Suggestion #3: create vector after count read in

// how many elements in the vector
int numberOfElems;
scanf("%d", &numberOfElems);

// declare vector and fill from stdin
int i, *vector;
size_t numberOfBytes;
numberOfBytes = numberOfElems * sizeof(int);
vector = (int *)malloc(numberOfBytes);
assert(vector != NULL);
for (i = 0; i < numberOfElems; i++) {
	scanf("%d", &vector[i]);
}

Works unless the heap is already full  (very unlikely)


The malloc() function9/16

Recall memory usage within C programs:

[Diagram:Pic/memusage-small.png]


... The malloc() function10/16

malloc() function interface

void *malloc(size_t n);

What the function does:

Note: size_t is essentially an unsigend int


... The malloc() function11/16

Example use of malloc:

[Diagram:Pic/malloc1-small.png]


... The malloc() function12/16

Things to note about   void *malloc(size_t):

Size is determined by   #Elements * sizeof(ElementType)


... The malloc() function13/16

malloc() returns a pointer to a data object of some kind.

Things to note about objects allocated by malloc():

The function free() releases objects allocated by malloc()


... The malloc() function14/16

Usage of malloc() should always be guarded:

int *vector, length, i;
...
vector = (int *)malloc(length*sizeof(int));
// but malloc() might fail to allocate
assert(vector != NULL);
// now we know its safe to use vector[]
for (i = 0; i < length; i++) {
	... vector[i] ...
}

Alternatively:


int *vector, length, i;
...
vector = (int *)malloc(length*sizeof(int));
// but malloc() might fail to allocate
if (vector == NULL) {
	fprintf(stderr, "Out of memory\n");
	exit(1);
}
// now we know its safe to use vector[]
for (i = 0; i < length; i++) {
	... vector[i] ...
}


Exercise: Creating Objects via malloc()15/16

Give variable declarations and statements that on the heap will create:

  1. a string buffer to hold strings of length K
  2. a vector of L double-precision floating point values
  3. an object of type Car, defined as:

    
    typedef struct {char rego[7]; float premium;} Car;
    

For each object:


Tips for Next Week's Lab16/16


Structured data types

3 exercises


Produced: 12 Aug 2016