I'm trying to figure out what would happened if I try to free a pointer "from the middle" for example, look at the following code:
char *ptr = (char*)malloc(10*sizeof(char));
for (char i=0 ; i<10 ; ++i)
{
ptr[i] = i+10;
}
++ptr;
++ptr;
++ptr;
++ptr;
free(ptr);
I get a crash with an Unhandled exception error msg. I want to understand why and how free works so that I know not only how to use it but also be able to understand weird errors and exceptions and better debug my codeץ
Thanks a lot
Taken from the book: Understanding and Using C Pointers
Never do this.
You're freeing the wrong address. By changing the value of ptr, you change the address. free has no way of knowing that it should try to free a block starting 4 bytes back. Keep the original pointer intact and free that instead of the manipulated one. As others pointed out, the results of doing what you're doing are "undefined"... hence the unhandled exception