How does free know how much to free?

后端 未结 11 2335
情话喂你
情话喂你 2020-11-22 03:28

In C programming, you can pass any kind of pointer you like as an argument to free, how does it know the size of the allocated memory to free? Whenever I pass a pointer to s

11条回答
  •  一个人的身影
    2020-11-22 03:56

    When you call malloc(), you specify the amount of memory to allocate. The amount of memory actually used is slightly more than this, and includes extra information that records (at least) how big the block is. You can't (reliably) access that other information - and nor should you :-).

    When you call free(), it simply looks at the extra information to find out how big the block is.

提交回复
热议问题