Why does free crash when called twice?

前端 未结 5 663
孤街浪徒
孤街浪徒 2020-12-09 09:20

In C and C++, free(my_pointer) crashes when it is called twice.

Why? There is bookkeeping of every malloc along with the size. When the f

5条回答
  •  臣服心动
    2020-12-09 10:03

    You say:

    not understood why. there is bookkeeping of every malloc() along with the size.

    Not necesarilly. I'll explain a bit about dlmalloc (used in glibc, uClibc, ...).

    Dlmalloc tracks blocks of free space. There cannot be two contiguous free blocks, they are merged immediately. Allocated blocks are not tracked at all! Allocated blocks have some spare space for bookkeeping info (size of this block, size of the preceding block and some flags). When an allocated block is free()'d, dlmalloc inserts it into a doubly-linked list.

    Of course, all of this is better explained at this dlmalloc article

提交回复
热议问题