Code gems

I’m sure everyone has their favorite examples of simple mistakes that are easy to do when you’re not yet fluent with the given programming language. if (a = 42) is quite legendary (did you mean ‘=’ or ‘==’ ?) but there are so many ways you can code wrong…

Here you can probably recognize the basic idiom(s) one was intending to use but got confused during implementation. Fun part is that this is not necessarily crashing:


mystruct->member = xmalloc(somelen+1);
memset(mystruct, '', sizeof(strlen(somestr)+1));
strncpy(mystruct->member, somestr, somelen);

Again, the intent is quite clear, but there’s something fishy in the implementation:


if (str[g_utf8_strlen(str, -1)] == '/')
  str[g_utf8_strlen(str, -1)] = '';

Semantics, schmemantics…