Critique my heap debugger

后端 未结 5 1380
梦谈多话
梦谈多话 2021-01-03 03:06

I wrote the following heap debugger in order to demonstrate memory leaks, double deletes and wrong forms of deletes (i.e. trying to delete an array with delete p

相关标签:
5条回答
  • 2021-01-03 03:32

    That's a really great start. Here's my 2 cents as you've asked for feedback:

    1. The code writes trace information to cerr, which is really for errors. Use cout for informational logs.
    2. The ALIGNMENT amount is arbitrary. If code tried to allocate 4090 bytes, you'd allocate 4106, which spills into the next 4k block, which is the size of a memory page. A calculated alignment value would be better... or rename ALIGNMENT as HEADER_SIZE or something similar.
    3. Given the header you're creating, you could store the size and a flag for the 'kind of memory' at allocation time and compare it at release time.
    4. Token should probably be called 'sentinel' or 'canary value'.
    5. Why is Token a size_t? Why not just a void * ?
    6. Your check for null in release should probably throw an exception instead - wouldn't it be an error if the code deleted a null pointer?
    7. Your 'correct_token' and 'wrong_token' values are far too similar. I had to re-read the code to be sure.
    8. Given point (3), you could double the amount you additionally allocate and have before and after sentinels/guard blocks. This would detect memory underrun and overrun.
    0 讨论(0)
  • 2021-01-03 03:43

    I'm not following your use of hardcoded constants/constant strings very well - put them in an enum? And I'm really not getting the idea of the token quite well. Needs more comments

    0 讨论(0)
  • 2021-01-03 03:50

    Explain why you chose "ALIGNMENT" as an identifier. Explain why you picked 16. Argue how your algorithm catches the most common mistakes, like overflowing the end of a heap-allocated block or forgetting to release memory.

    0 讨论(0)
  • 2021-01-03 03:50
    void* raw = static_cast<char*>(payload) - ALIGNMENT;
    

    If payload has been already deleted, wouldn't that make this undefined behavior?

    0 讨论(0)
  • 2021-01-03 03:55

    Instead of doing intrusive note-keeping you could keep a list of all allocations made. Then you can free the memory without destroying your own data, and keep track of how many times a particular address is "deleted", and also find places where the program tries to delete a non-matching address (i.e. not in the list).

    0 讨论(0)
提交回复
热议问题