/* CSE 374 Winter 2014 Lecture 10, Slide 7 Example */ #include #include int main() { /* malloc returns NULL if the request cannot be satisfied */ /* free on a NULL pointer does nothing */ /* only use free on a pointer that points to memory allocated by malloc or calloc */ int *p = (int *) malloc(sizeof(int)); p = NULL; /* LEAK - forgot to free the memory pointed at by p first */ int *q = (int *) malloc(sizeof(int)); free(q); /* free(q); */ /* this memory has already been freed, may cause a crash */ /* comment out the second "free(q)" if this program crashes */ int *r = (int *) malloc(sizeof(int)); free(r); /* allocated and then freed memory */ /* allocate some memory, have s point to it, and store the value 19 */ int *s = (int *) malloc(sizeof(int)); *s = 19; printf("*s is %d\n", *s); /* it is an error to use a pointer after it has been freed */ /* (we already freed r and attempt to use it again below) */ /* the memory pointed to by s was allocated immediately after the memory pointed to by r was freed. It could be possible that malloc allocates the same block of memory again. */ /* could crash, but what if s == r ? */ *r = 17; printf("*s is %d\n", *s); /* experiment with this in gdb */ /* compile with gcc -g -Wall options */ /* set a breakpoint at main */ /* display p, q, r, and s (separate display commands) to see the addresses assigned */ /* step through the program a line at a time */ return 0; }