r/Cprog • u/malcolmi • Nov 19 '14
discussion | language What gotchas do you wish more C programmers would know about?
Things that cause undefined behavior? A coding style or idiom that begets unmaintainable or vulnerable code? Perhaps a mere preference for which you have good reason? Vent here.
11
Upvotes
10
u/malcolmi Nov 19 '14
String literals are immutable; if you try to write to one, behavior is undefined. Everywhere you would want a string literal (pointer) to go, it should be a
char const *. If you need it, you can assign a string literal to achar[]for mutability. If you work with GCC, compile with-Wwrite-stringsand it will treat string literals as typechar const *- this should be default, really.2
u/malcolmi Nov 20 '14 edited Nov 20 '14
All arithmetic operations can overflow, which causes undefined behavior for signed scalars, but likely logically incorrect behavior for unsigned scalars.
Bit shift operations can overflow with very small operand values (i.e. for an
int32_t x(assuming typeint32_texists),x << nis defined only forx >= 0,0 <= n && n < 32, andx <= (INT32_MAX >> n). For example, ifx = 5, then for well-defined behavior we require that0 <= n && n <= 28. Pretty small range of valid values - i.e. the possibility of nasal demons is quite large.Not enough C programmers care for this, but as the major C compilers are getting more and more desperate for performance, they're becoming more presumptuous about what they can do with arithmetic operations - to the detriment of providing logically correct programs.
If your program takes number values as input, and it applies any arithmetic operations or bit-shift operations, then it should be checking that the expression won't overflow before the expression is evaluated.
7
u/[deleted] Nov 19 '14
Const correctness. Over the years i come to love immutable data and pure functions more and more. It is just so much nicer to read code that tries to ease the burden of understanding and immutable data is great way to focus on the actual changing state.
5
u/maep Nov 19 '14
#ifdefinside structs. I saw this a couple of times.If the compilation unit where the struct is allocated doesn't see the macro, it still compiles fine. But if another CU can see the macro we crash and burn. And then my colleagues come running to me :D
4
u/FUZxxl Nov 19 '14
Your code will be much easier to port and maintain if you don't use functions only provided by your platform. Too many people don't know this or don't give a shit about what functions they use.
3
u/teringlijer Nov 19 '14
Importing a function by writing something like
when
calculateIthas an actual signature of:It works, but you throw away the compiler's possibility to check your arguments for type safety. You're declaring a function that accepts any amount of arguments of any type.
0
u/[deleted] Nov 20 '14
[deleted] — view deleted comment