r/cprogramming • u/EqualTumbleweed512 • 5h ago
Why is the -fsanitize flag increasing the memory my binary uses
I heard that `-fsanitize` flag can detect memory errors so I used it with on my project. `-fsanitize=address,undefined`, but when I looked in my system monitor, I saw that the the memory it used kept increasing.
I reviewed my code to see if the code had any memory leaks, but it didn't.
I compiled the project without that flag and now the memory usage didn't increase and it used only half the memory it used with the flags, which is fair
Is this common behavior?
6
Upvotes
8
u/EpochVanquisher 5h ago
The address sanitizer uses “shadow memory” to track the state of the memory your program uses. The shadow memory takes an equal amount of space as normal memory. This means that a program using the address sanitizer uses about 2x memory as the same program without the address sanitizer.
This is completely normal and expected. If the sanitizer were free, people would just leave it on all the time. Because it costs memory, there is a switch to turn it on, and it’s off by default.
6
u/epasveer 4h ago
For development work, what does it matter? It's helping you find your bugs.
Turn it off when you make a release version.
24
u/flyingron 5h ago
Because it has to both increase the code size to add the instrumentation and checks, and it has to have some additional memory to keep track of what is going on. This is 100% expected.
4
u/opposite-badge 5h ago
As far as I know the basic trick at detecting memory leaks is to allocate more memory than what is asked by the program and check if the program tries to access the parts of memory that were not assigned to it.
Eskil Steenberg has some video on Youtube where he talks about how he detects memory related bugs.
3
u/FancySpaceGoat 4h ago
If it could be done for free, it wouldn't be an optional flag.
That's a pretty good rule of thumb in general with compilers. If it's an option, there's always a catch.
1
u/Key_River7180 4h ago
Asan keeps track of everything, only enable it for debug builds
1
u/pdath 1h ago
A typical flow is to enable sanitisers, then run your unit tests and any fuzzers.
You turn it off again when making a production binary.