No malloc() implementation should prevent you from trying to write the past that you highlighted. It is assumed that if you allocate 123 bytes, you will use all or less of what you allocated. malloc() , for efficiency, should assume that the programmer will keep track of their pointers.
Using memory that you haven't explicitly set and asked malloc() to give you undefined behavior. You may have requested n bytes, but received n + x, due to optimizing the implementation of malloc() to align the bytes. Or you can write in a black hole. You can never know why this behavior is undefined.
It is said ...
There are versions of malloc() that give you built - in statistics and debugging , however they should be used instead of the standard malloc() , as if you were using a garbage collector .
I also saw options specifically designed for LD_PRELOAD that expose a function that allows you to define a callback with at least one void pointer as an argument. This argument assumes a structure containing statistics. Other tools, such as an electric fence , will simply stop your program from giving exact instructions that lead to overflow or access to invalid blocks. As @R .. notes in the comments, this is great for debugging, but terribly inefficient.
Itβs fair for everyone or (as they say) βat the end of the dayβ - itβs much easier to use a heap profiler, for example Valgrind and related tools ( massif ) in this case, which will give you quite a lot of information. In this particular case, Valgrind would point out the obvious - you wrote the previously highlighted border. In most cases, however, when this is not intentional, a good profiler / error detector is priceless.
Using a profiler is not always possible because of:
- Problems with synchronization while working under the profiler (but they are common when all calls to
malloc() intercepted). - Profiler is not available for your platform / arch
- Debugging data (from the
malloc() log) should be an integral part of the program
We used the library option that I linked in HelenOS (I'm not sure they still use it) for quite some time, since, as you know, debugging in VMM is crazy.
However, think about future consequences when considering replacing, when it comes to the malloc() object, you almost always want to use what the system sends.