[haiku-development] Re: malloc/free

  • From: "Adrien Destugues" <pulkomandy@xxxxxxxxxxxxx>
  • To: haiku-development@xxxxxxxxxxxxx
  • Date: Thu, 05 Oct 2017 14:40:25 +0000

5 octobre 2017 16:33 "Sean Healy" <jalopeura@xxxxxxxxxxx> a écrit:

On Tue, 03 Oct 2017 22:28:28 -0700, Adrien Destugues 
<pulkomandy@xxxxxxxxxxxxx> wrote:

It may be a problem in some code around yours which ends up corrupting
the memory allocator data structures.

Usually a good start is using malloc_debug to try to catch these errors:
https://www.haiku-os.org/blog/mmlr/2010-02-08_using_malloc_debug_find_memory_related_bugs

Turns out I was writing past the end of another piece of malloc'd data in
the surrounding code. Not sure 1) why my previous version of Haiku didn't
choke on that, or 2) why it didn't choke on it when I overwrote, but
waited until the call to free (which freed a different address, at that!)

The hardware memory protection is not perfect and byte-for-byte. It works with 
pages of 4 kilobytes.

The memory allocator will not reserve a single one of these pages for each 
allocation you do (that would waste too much space). In case of small 
allocations, the page may be shared between multiple ones. At the end of it, 
there is a small data structure used by the memory allocator itself to keep 
track of the allocations. This is what you overwrote.

When you call free or malloc, the allocator may need to use that data structure 
(to look for a block with free space, or to merge two adgacent blocks into a 
larger one, for example). Only then it needs the data you erased, and this 
leads to the crash.

As mentionned in the article I linked, with libroot_debug you can manually 
trigger a check of the heap state, which would help detecting such problems. 
The allocator itself will also be more paranoid and check stuff whenever it 
can. However, we don't do this by default, because the performance cost would 
be too high. So, you must enable it when debugging such problems.

-- 
Adrien.

Other related posts: