Does free releases the memory in the below, and how can I verify that memory is released ?
int *p = malloc(sizeof(int)); int *q = p; free(q); How to access MCB structure for a dynamically allocated memory ?
Def of free()::
void free (void* ptr); Deallocate memory block
A block of memory previously allocated by a call to malloc, calloc or realloc is deallocated, making it available again for further allocations.
If ptr does not point to a block of memory allocated with the above functions, it causes undefined behavior.
If ptr is a null pointer, the function does nothing.
Notice that this function does not change the value of ptr itself, hence it still points to the same (now invalid) location.
So, in that case, if you try to access the freed memory through the pointer which still points to the same location, it would cause "undefined behavior". You can verify the same by invoking this undefined behavior( for Experimental pupose only ) or you can use Valgrind to verify. If you are using Visual studio, you can add a watch to the pointer q and see for yourself the memory layout and freeing of the block.
As per your code the memory will be released, But if you change the pointer q other than initial pointer p. It will not work.
For explanation: When you call malloc() you pass the amount or size to allocate memory, But in reality the memory is allocated more than size because memory allocator stores some meta information of this allocation. So when you call free with the initial pointer of the given malloced region the free() function is able to get this info & so memory is deallocated. But if you pass the pointer other than the initial pointer of the allocated region it will not get this meta info & free() will fail.!!!
freewill always release the memory space pointed to byp, regardless of whether you have made copies ofp. There is no point verifying it asfreecannot fail on valid pointers (obtained through*alloc). And you are not supposed to access the MCB.