/* * heap.c * * Computer Science 50, Fall 2011 * section4 * * Working with variables created in the heap. */ #include #include // functions prototypes int* f(); int* g(); int main(void) { // creates a pointer to a variable created in f() int* x = f(); printf("x has the value %d\n", *x); // creates a pointer to a variable created in f() int* y = g(); printf("x (still) has the value %d\n", *x); printf("y has the value %d\n", *y); // always remember to do this! free(x); free(y); } int* f() { // declares a pointer int* a; // reserves some space in the heap do { // sets 'a' equal to the address of the reserved space a = malloc(sizeof(int)); } while(a == NULL); // goes until we're sure we got some space // sets the space 'a' points to equal to 5 *a = 5; // returns the value of a (i.e. the address of the space in the heap) return a; } int* g() { // see comments in f() int* b; do { b = malloc(sizeof(int)); } while(b == NULL); *b = 10; return b; }