How do free and malloc work in C?

2019-01-01 12:42发布

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

8条回答
人间绝色
2楼-- · 2019-01-01 13:11

Taken from the book: Understanding and Using C Pointers

When memory is allocated, additional information is stored as part of a data structure maintained by the heap manager. This information includes, among other things, the block’s size, and is typically placed immediately adjacent to the allocated block.

查看更多
路过你的时光
3楼-- · 2019-01-01 13:15

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

查看更多
登录 后发表回答