Checking if something was malloced

后端 未结 8 679
面向向阳花
面向向阳花 2021-01-12 07:06

Given a pointer to some variable.. is there a way to check whether it was statically or dynamically allocated??

8条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-12 07:17

    Most libc malloc implementations work by storing a header before each returned memory block which has fields (to be used by the free() call) which has information about the size of the block, as well as a 'magic' value. This magic value is to protect against the user accidently deleting a pointer which wasn't alloc'd (or freeing a block which was overwritten by the user). It's very system specific so you'd have to look at the implementation of your libc library to see exactly what magic value was there.

    Once you know that, you move the given pointer back to point at header and then check it for the magic value.

提交回复
热议问题