My question is very simple one. Say we have:
char* ptr = (char*) malloc(sizeof(char)*SIZE);
ptr+= SIZE/2;
free(ptr);
What happens when we free the pointer? Is it undefined operation? Does it free all of SIZE buffer or only the remaining SIZE/2? Thanks in advance for disambiguating this for me.
Yes, when you use a free(px); call, it frees the memory that was malloc'd earlier and pointed to by px. The pointer itself, however, will continue to exist and will still have the same address.
The function free takes a pointer as parameter and deallocates the memory region pointed to by that pointer. The memory region passed to free must be previously allocated with calloc , malloc or realloc . If the pointer is NULL , no action is taken.
When a pointer is incremented, it actually increments by the number equal to the size of the data type for which it is a pointer. For Example: If an integer pointer that stores address 1000 is incremented, then it will increment by 2(size of an int) and the new address it will points to 1002.
Address arithmetic is a method of calculating the address of an object with the help of arithmetic operations on pointers and use of pointers in comparison operations. Address arithmetic is also called pointer arithmetic.
Your program will probably crash: the free() operation is actually quite simple in C, but works only on the original allocated address.
The typical memory allocator works like this pseudo code:
So when you call free(ptr)
, the allocator goes 6 bytes before your pointer to check for the signature. If it doesn't find the signature, it crashes :)
If the argument to free()
does not match a pointer previously allocated by means of malloc()
and friends, the behaviour is undefined. You will most likely encounter a segmentation fault or a failed assertion in your version of libc
.
Offtopic: it's better you didn't cast the result of malloc()
in C.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With