Are there any tools or methods that can identify buffer overruns in statically defined arrays (ie. char[1234]
rather than malloc(1234)
)?
I spent most of yesterday tracking down crashes and odd behaviour which ultimately turned out to be caused by the following line:
// ensure string is nul terminated due to stupid snprintf
error_msg[error_msg_len] = '\0';
This index obviously caused writing beyond the bounds of the array. This lead to the clobbering of a pointer variable, leading to unexpected behaviour with that pointer later on.
The three things that come to mind that could help alleviate such problems are:
Code review
This wasn't done, but I'm working on that.
valgrind
I often use valgrind during development to detect memory problems but it does not deal with static arrays. In the above instance it only showed me the symptoms such as the invalid
free()
of the clobbered pointer.-fstack-protector-all
In the past I have used
-fstack-protector-all
to detect overruns like the above but for some odd reason it didn't flag anything in this instance.
So can anyone offer any ideas on how I could identify such overruns? Either by improving on the above list or something completely new.
EDIT: Some of the answers so far have mentioned commercial products that are fairly expensive. At this stage I don't think I could convince the powers that be to buy such a tool so I'd like to restrict tools to cheap/free. Yes, you get what you pay for but some improvement is better than none.
Static analyzer tools are able to detect some buffer overflows.
For example with this code:
Here is what PC-Lint / flexelint reports: