Oh ok, I thought the important thing was that the argument of free pointed to memory that had been malloc'ed. I did not realize that the argument itself had to have been initialized with malloc.

What about the following code:

int *makePointer (VOID)
{
int *p = malloc(sizeof(int) * 10);
return p;
}

int main ()
{
int *ptr;
ptr = makePointer();
}

Can I call free with the argument ptr in main? If I cannot, then how do I free up the memory?

And what if I wrote the following:

int *p = malloc(sizeof(int) * 10);
int *q = malloc(sizeof(int) * 9);
p = q;
free(p);

Is the malloced memory of size 10 freed? Or of size 9? Or is the behavior undefined?

What if I had a pointer p that had been initialized with malloc and then I assigned it to point to a different address, but did not save the original address. Does that mean I can no longer free the memory?

What if I had a pointer p that had been initialized with malloc , I stored the address in a variable x, then I assigned p to point somewhere else, then I reassigned p to point to the address stored in x. Then can I call free with argument p to free up that memory?

Does anyone know where I can read an in depth explanation of some of these details? It is really bugging me.