Recently, I came across a very insightful error in which I forgot to dereference a pointer to a string (char array) and thus sometimes overwrite one byte on the stack.
Poorly:
char ** str; (*str) = malloc(10); ... str[2] = 'a';
Fixed:
char ** str; (*str) = malloc(10); ... (*str)[2] = 'a';
GCC did not issue any warnings, and this error would lead to a very serious and real exploit, since the value that it sometimes overwritten contained the size of the buffer. I just caught this error because I was lucky and it caused a clear failure.
Also, to rely on luck and / or never use C for anything, what protective methods and coding tricks do you use to catch creepy C errors?
I'm thinking of switching to valgrind MemCheck , has anyone used it? I suspect I would not catch this mistake. Somebody knows?
Are there tools for finding dereferencing pointers or arithmetic errors? Is it possible?
UPDATE
Here is the requested sample code; it does not give any warnings.
#include <stdlib.h> void test(unsigned char** byteArray){ (*byteArray) = (unsigned char*)malloc(5); byteArray[4] = 0x0; } int main(void){ unsigned char* str; test(&str); return 0; }
Compilation does not cause errors:
gcc -Wall testBug.c -o testBug
Running causes a seg error:
./testBug Segmentation fault
This is the version of GCC I am using:
gcc -v Using built-in specs. Target: i486-linux-gnu Configured with: ../src/configure -v --with-pkgversion='Ubuntu 4.4.1-4ubuntu9' --with-bugurl=file:///usr/share/doc/gcc-4.4/README.Bugs --enable-languages=c,c++,fortran,objc,obj-c++ --prefix=/usr --enable-shared --enable-multiarch --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.4 --program-suffix=-4.4 --enable-nls --enable-clocale=gnu --enable-libstdcxx-debug --enable-objc-gc --enable-targets=all --disable-werror --with-arch-32=i486 --with-tune=generic --enable-checking=release --build=i486-linux-gnu --host=i486-linux-gnu --target=i486-linux-gnu Thread model: posix gcc version 4.4.1 (Ubuntu 4.4.1-4ubuntu9)
c pointers findbugs
Ethan heilman
source share