The purpose of the model is to allow us to run our

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: In this case, malloc allocates a portion of the block that was freed in the previous step and returns a pointer to this new block. 10.9.2 Why Dynamic Memory Allocation? The most important reason that programs use dynamic memory allocation is that often they do not know the sizes of certain data structures until the program actually runs. For example, suppose we are asked to write a C program that reads a list of Ò ASCII integers, one integer per line, from stdin into a C array. The input consists of the integer Ò, followed by the Ò integers to be read and stored into the array. The simplest approach is to define the array statically with some hard-coded maximum array size: 10.9. DYNAMIC MEMORY ALLOCATION 525 p1 (a) p1 = malloc(4*sizeof(int)) p1 p2 (b) p2 = malloc(5*sizeof(int)) p1 p2 p3 (c) p3 = malloc(6*sizeof(int)) p1 p2 p3 (d) free(p2) p1 p2 p4 p3 (e) p4 = malloc(2*sizeof(int)) Figure 10.36: Allocating and freeing blocks with malloc. Each square corresponds to a word. Each heavy rectangle corresponds to...
View Full Document

This note was uploaded on 09/02/2010 for the course ELECTRICAL 360 taught by Professor Schultz during the Spring '10 term at BYU.

Ask a homework question - tutors are online