#include #include /* A short description of the function, if necessary */ int main (int args, char *argv[]) { int *ptr; // here, star means pointer type int a = 5; ptr = &a; // ptr now had the value of the address of a. // Here, star means follow the pointer and access what is // at the end of it. printf( "a is %d and ptr points to %d\n", a, *ptr ); printf( "ptr has the value %p\n", ptr ); printf( "ptr is at address %p on the stack\n", &ptr ); ptr = malloc( sizeof(int) ); *ptr = 6; printf( "a is %d and ptr points to %d\n", a, *ptr ); printf( "ptr has the value %p\n", ptr ); // create a memory leak ptr = &a; ptr = malloc( sizeof(int) ); *ptr = 7; printf( "ptr has the value %p\n", ptr ); free( ptr ); // this time, free the memory first. // so now, the 7's spot is available for more mallocing but the // 6's spot never will be. // dereferencing a freed pointer is not something we are supposed to do // it leads to undefined behavior // I wish it caused an error, but it doesn't :( // ptr is what we call a "dangling reference" printf( "after free, ptr has the value %p\n", ptr ); printf( "a is %d and ptr points to %d\n", a, *ptr ); // malloc tends to reuse memory spots, so it is likely to return // the address that ptr just freed (no guarantees, though!) int *ptr2 = (int *)malloc( sizeof(int) ); printf( "ptr2 has the value %p\n", ptr2 ); *ptr2 = 8; printf( "ptr points to %d and ptr2 points to %d\n", *ptr, *ptr2 ); if (ptr == ptr2) { printf( "ptr and ptr2 have the same value, so point to the same address\n" ); printf( "*ptr is %d and *ptr2 is %d\n", *ptr, *ptr2 ); } else { printf( "ptr and ptr2 have addresses %ld far apart\n", ptr-ptr2 ); } // ptr = malloc( sizeof(int) ); // *ptr = 8; // printf( "a is %d and ptr points to %d\n", a, *ptr ); // printf( "ptr has the value %p\n", ptr ); }