ECE 209 -- Heap

Typical segment layout for C

Text Contains the compiled code of the main program, its subroutines, and any static libraries. Fixed size
Data Often considered to have three parts: (1) The data area contains initialized variables with static duration. (2) The BSS area contains uninitialized variables with static duration. (3) The heap contains data allocated and freed explicitly by the running program. Data and BSS areas are fixed size. Heap can grow and shrink.
Stack Contains variables of automatic duration. Grows with function calls. Shrinks with function returns.

Views of memory allocation

The real world

Memory allocation in C

Example of dynamic memory use

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

int main(int argc, char** argv) {
    int numberToReverse ;
    printf("How many to reverse?\n") ;
    while (scanf("%d", &numberToReverse)==1
            && numberToReverse > 0) {
        int i ;
        int *ReverseThese ;
        if ((ReverseThese=(int *)malloc(numberToReverse*sizeof(int)))
                == NULL) {
            printf("Too big\n") ;
            return(EXIT_FAILURE) ;
        }
        for(i=0; i < numberToReverse; ++i) {
            printf("Enter number %4d\n", i) ;
            scanf("%d", &ReverseThese[i]) ;
        }
        for(i=numberToReverse-1; i >= 0; --i) {
            printf("Number %4d: %8d\n", i, ReverseThese[i]) ;
        }
        free(ReverseThese) ;
    }
    return (EXIT_SUCCESS);
}

Safe and unsafe dynamic memory use

Now for something completely different from Chapter 12

Why are all those volatile's necessary?

/* Based on the Keyboard Echo example from Patt and Patel (p. 207) */
volatile int * KBSR = (int *) 0xFE00 ;
volatile int * KBDR = (int *) 0xFE02 ;
volatile int * DSR  = (int *) 0xFE04 ;
volatile int * DDR  = (int *) 0xFE06 ;
int NewChar ;

while (*KBSR > 0) /*spin*/ ;
NewChar = *KBDR ;

while (*DDR  > 0) /*spin*/ ;
*DDR  = NewChar ;