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. |
void *
malloc(NumberOfBytes)
calloc(NumberToAllocate, SizeOfEach)
free(MemoryAddress)
#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); }
NULL
return
if ((p=malloc(10000)) == NULL) { fputs("Out of memory\n", stderr) ; exit(1) ; }
void *
as needed
char *p ; if ((p=(char *)malloc(10000)) == NULL) { ................ ................ free((void *)p) ;
sizeof
for safety and portability
int *p ; ................ if ((p=(int *)malloc(10000 * sizeof(int))) == NULL) { ................ if ((p=(int *)malloc(10000 * sizeof *p)) == NULL) { ................ if ((p=(int *)calloc(10000, sizeof(int))) == NULL) {
int *p, *q ; .... if ((p=(int *)calloc(10, sizeof(int))) == NULL) { .... q = p ; .... free(p) ; /* q becomes a dangling pointer */ .... printf("%d\n", *q) ;
int DoSomething(int a) { int *p ; .... if ((p=(int *)calloc(10, sizeof(int))) == NULL) { .... /* p is lost memory */ return 5 ; }
BigObject p = new BigObject(209, 2009) ; ................ delete p ;
BigObject p = new BigObject(209, 2009) ;
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 ;