wiki:SafeCoding

Some hints on creating safe code

When you make assumptions in your mind, make assertions in your code.

  • During coding you make assumptions all the time, e.g. something like "that idx will be in the range [X..Y] here".
  • Put such assumptions into your code as assertions:
    arb_assert(idx>=X && idx<=Y);
    
    This will not make the released code slower, cause it will not be compiled in there, but it will make it much easier to find bugs and even make your code more readable.
  • Do NOT write it as
    if (idx>=X && idx<=Y) { // just to be sure
        do_sth();
    }
    
    If you want to be on the safe side in release version (because your assumption is very important), write
    arb_assert(idx>=X && idx<=Y);
    if (idx>=X && idx<=Y) { // just to be sure it does not happen in release
        do_sth();
    }
    
    or better implement proper error handling:
    GB_ERROR error = 0;
    if (idx>=X && idx<=Y) {
        do_sth();
    }
    else {
        error = "idx out of bounds";
    }
    return error;
    

When you write code please valgrind it afterwards to make sure it doesn't do evil things.

  • The necessary software is installed on waltz (e.g.)
  • there's a skript called arb_valgrind in $(ARBHOME)/SOURCE_TOOLS which makes valgrinding a bit easier (especially for emacs users). If you call it as compiler, emacs can parse the output as errors and easily jump to the suspicious code locations.
    This skript also filters out warnings about internal Motif concerns.

If release version behaves different than DEBUG version:

  • DEBUG version is compiled with optimization level 0 (flag '-O0'), release version is compiled with level 4 (flag '-O4'). Since gcc generates very different code for different optimization levels, you should as well valgrind with different optimization levels.
    To do this
    • temporarily change the -O0 flag in the DEBUG section at start of $(ARBHOME)/Makefile to your desired level
    • and recompile ARB.

Last modified 11 years ago Last modified on May 24, 2007, 11:01:00 PM