Stupid mistakes in C programming

These are some stupid mistakes I made programming C.

strlen ("\0");

I used strlen ("\0") in malloc as a substitute for 1. This is stupid because it gives a value of zero. The correct way to do this is to write sizeof ((char) '\0').

Added to a pointer twice

I added an offset to a pointer twice instead of once. Notice how cur is added to svbuf and then added again in the call to memcpy in the following: JSON::Parse pointer arithmetic error on Github. This led to segmentation fault errors when the Perl module was parsing long JSON strings containing escape characters like \n.

Used sizeof (unsigned int *) to bsearch an array of unsigned integers

Given an array of unsigned integers,

unsigned int * keys; // something like 1, 2, 3

I searched them with bsearch using sizeof (unsigned int *) for the "size of element" parameter:

found = bsearch (word, keys, n_keys, sizeof (unsigned int *), compare);

This actually worked perfectly well on the 32 bit computer, but on a 64-bit computer, when the size of an unsigned int was different from the size of a pointer to unsigned int, it caused all kinds of mystery crashes.

Copyright © Ben Bullock 2009-2023. All rights reserved. For comments, questions, and corrections, please email Ben Bullock ( or use the discussion group at Google Groups. / Privacy / Disclaimer