I use malloc to allocate memory which is used by a pointer type. And then I forcefully modify pointer type. use free func to release the memory block. I am curious to know whether memory leak happens?
I thought memroy was free by pointer type. "int *b" has wider range memory block than "char *a". I compile the following code and run it. No expection happens. Could somebody tell me what happens and why?
#include <stdlib.h>
int
main(int argc, char **argv) {
char *a = (char*)malloc(sizeof(char));
int *b = (int*)a;
free(b);
}
The routines in the malloc
family keep track of all the memory they reserve, including the sizes. When you pass an address to free
, the routines look up the address in their records and release the amount of space that was allocated for it.
free
is only passed an address. It has no information about the type of the pointer that the caller used as an argument. Because free is declared as void free(void *)
, any pointer passed to it is automatically converted to void *
, and free receives only that void *
, not any information that it came from an int *
or other type.