/* This example was generated by Bob Beck and has been only lightly * edited for presentation here. The sample output was produced under * CodeWarrior C/C++ compiler running on a PPC processor (not OpenBSD) * Students are free to download this example for testing purposes. */ #include #include /* for malloc() and friends. */ /* memory.c - A few examples of dynamic memory allocation for OpenBSD. * * compile this program (g++ -Wall -ansi -o memory memory.c), then do a * * setenv MALLOC_OPTIONS J * ./memory * * The moral of the story is never trust malloc() to zero memory for you. * */ #define CHUNKSIZE 10 /* we'll allocate this much at once */ int main() { int i, j; char * fred; char * george; char * tmp; char sally[CHUNKSIZE]; fred = (char *) malloc (CHUNKSIZE * sizeof(char)); /* we must *always* check the return values of malloc and friends * - they will fail if inadequate memory space available */ if (fred == NULL) { fprintf(stderr, "Malloc barfed\n"); exit(1); } george = (char *) calloc (CHUNKSIZE, sizeof(char)); if (george == NULL) { fprintf(stderr, "Calloc barfed\n"); exit(1); } printf ("sally(%p), statically allocated has byte values: ", sally); for (i = 0; i < CHUNKSIZE; i++) printf("%d ", sally[i]); putchar('\n'); printf ("fred(%p), from malloc has byte values: ", fred); for (i = 0; i < CHUNKSIZE; i++) printf("%d ", *(fred+i)); // this is also fred[i] putchar('\n'); printf ("george(%p), from calloc has byte values: ", george); for (i = 0; i < CHUNKSIZE; i++) printf("%d ", *(george+i)); // this is also george [i] putchar('\n'); /* grow george to make him CHUNKSIZE bigger */ j = CHUNKSIZE + CHUNKSIZE; tmp = (char *) realloc(george, j * sizeof(char)); if (tmp == NULL) { /* Important - when realloc fails, it returns NULL, but leaves * george unchanged (man 3 realloc for details) - if we had done: * george = realloc(george, j * sizeof(char)) * we would have lost the memory segment pointed to by george, since we * would have changed george's value to NULL. This doesn't matter * if our program is going to exit, but does matter if we are * going to continue and not have a memory leak. */ fprintf(stderr, "realloc failed - george left unchanged\n"); j = CHUNKSIZE; } else { george = tmp; } printf ("george(%p), from realloc has byte values: ", george); for (i = 0; i < j; i++) printf("%d ", george[i]); putchar('\n'); /* we should free dynamically allocated memory when done with it */ free(george); free(fred); /* but we don't free statically allocated memory - a * free(sally) will cause problems. */ return (0); } /* Sample output sally(0x05dc9558), statically allocated has byte values: 0 0 0 0 0 0 0 9 5 -30 fred(0x05d548b0), from malloc has byte values: 5 -43 72 -68 0 0 0 0 0 0 george(0x05d548c0), from calloc has byte values: 0 0 0 0 0 0 0 0 0 0 george(0x05d55860), from realloc has byte values: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 */