开发者

How MMU detects double free of a pointer?

开发者 https://www.devze.com 2022-12-20 05:54 出处:网络
How the memory management unit(MMU) detects the double free of a pointer? I know that its a good pr开发者_如何学JAVAactice to make the pointer NULL just after freeing it, but suppose programmer does

How the memory management unit(MMU) detects the double free of a pointer?

I know that its a good pr开发者_如何学JAVAactice to make the pointer NULL just after freeing it, but suppose programmer does not do it. Is there any MMU mechanism to detect it?


The MMU has nothing to do with it. If you free a pointer allocated with malloc twice you will probably corrupt the C runtime heap. The heap (not the MMU) can in principle protect itself against such things, but most don't. Please note that this has nothing to do with the operating system - neither malloc() nor free() are system calls.


How the memory management unit(MMU) detects the double free of a pointer?

The MMU just does virtual address space -> physical memory mapping, it doesn't know anything about how the heap is organized/how the allocation works/..., that is operating system/allocator work.

How does OS detects the double free then? Whats the mechanism??

It walks the list/bitmap/... of allocated blocks, sees that there's no allocated block with the address you passed to it, so it detects that it's a double free.

However if that block has already been re-allocated, it finds it and correctly free it => but now the code that used the re-allocated block will go nuts, since the memory it has correctly acquired and that it didn't release has become unallocated.

If the allocator protects the unallocated memory marking it as no-read and no-write/removing it from the committed pages of the virtual address space the program will die as soon as that memory is accessed again (but the code that apparently caused the crash will be actually innocent, since it didn't do anything wrong).

Otherwise, the application may still work for some time, until that memory block will be given to some other piece of code that requested some memory. At that point, two pieces of the same application will try to work on the same block of memory, with all the mess that can originate from this.

(Thanks to Pascal Cuoq for pointing out my error.)


No, there is no MMU mechanism to detect it. It is common that calling free on an already free'd address causes the program to crash as the implentation of free does something unexpected and causes a segmentation fault.

Running valgrind is a good way of checking for memory management problems, such as double freeing a pointer.


Setting it to NULL isn't actually a good practice, it hides bugs. Particularly double free()s. Check the OS memory map, something like 0xfeeefeee or 0xdeadbeef is usually good.

You can diagnose double free()s with a debug allocator. Most any decent CRT has one.

0

精彩评论

暂无评论...
验证码 换一张
取 消