0

I want to discover (for debug purpose) any possible cause of memory failure of my C++ program. Should I limit the heap size? Should I infinite loop a dynamic memory allocation (new) until crash? i want to cause a bad_alloc error without throwing it manually in order to discover something i may not have noticed.

  • If your application is 64 bit you may have a difficulty seeing a bad_alloc unless you attempt to allocate a ridiculous amount of memory. On MS Windows the infinite loop may just bring the OS to a crawl. On linux the OOM Killer may just kill your application. – drescherjm Aug 29 '22 at 22:05
  • 3
    One could overload the global `operator new`, and have it randomly throw `bad_alloc`. – Sam Varshavchik Aug 29 '22 at 22:16
  • With MSVC you can cause a particular allocation to fail by using _CrtSetAllocHook and returning FALSE (0) from the installed hook. This way you can test handling all through your program (for instance by having a flag the hook checks) and not just during initialization or shutdown. – SoronelHaetir Aug 29 '22 at 22:24
  • Have a look at [AddressSanitizers](https://stackoverflow.com/questions/37970758/how-to-use-addresssanitizer-with-gcc) and the other ```-fsanitize``` options that you can use in gcc and clang. – francesco Aug 29 '22 at 22:45
  • 1
    On Linux you can put your program into a control group with limited maximum memory. – user253751 Aug 29 '22 at 23:44
  • @francesco it looks a lot like valgrind (which i'm already using to detect memory leaks). the problem is that these programs are made to find errors only if they occurs. It means that if you have enough memory (99.99% with my low memory classes) you will never have a memory exception. BUT i MUST test also for heavy classes, which means the program could crash in their first new, or second, or third, or 20th... i have to check every possible 'new' – Yronbird Aug 31 '22 at 14:13
  • @SamVarshavchik not bad (is it legal?) but: let's say that a class makes 10 "new"s: 1) can crash 2) can crash 3) can crash 4) ... with your solution i think it would crash at point 1 and i'll never find point 2,3,4... – Yronbird Aug 31 '22 at 14:17
  • The key word in my previous comment was "randomly". – Sam Varshavchik Aug 31 '22 at 14:21
  • @user253751 maybe a bit hardcoded and not "automatic" (my fear would be to manually recompile with different memory sizes for every test, it would exponentially increase work times) but not bad, how can i do that? – Yronbird Aug 31 '22 at 14:23
  • @SamVarshavchik my bad for not having caught that detail! How would you implement that? something like a simple random value and an if? – Yronbird Aug 31 '22 at 14:26
  • I would implement it as a basic random generator with its own seed, that's independent of `rand()` and friends, and the means to log each run's seed, as well as force a seed for a particular program run. – Sam Varshavchik Aug 31 '22 at 14:32

0 Answers0