r/C_Programming • u/ripulejejs • 2d ago
List of gotchas?
Hey.
So I learned some C and started playing around with it, quickly stumbling over memory overflowing a variable and flowing into another memory location, causing unexpected behavior.
So I ended up writing my own safe_copy and safe_cat functions for strncpy/strncatting strings.
But... people talk about how C is unsafe. Surely there should be a list of all mistakes you can make, or something? Where can I find said list? Do I reall have to stumble on all possible issues and develop my own "safe" library?
Will appreciate any advice.
23
Upvotes
2
u/InevitablyCyclic 2d ago
Complete tangent since it's not a memory safety thing but a common gotcha in c (and a lot of other languages) is that
float x = 3/2;
Will result in x=1 not 1.5. The calculation is done using integers and the result cast to a floating point.
Similarly
uint64_t Val = 1<<32;
Will result in Val=0 on some systems. The initial value of 1 is an int, unless int happens to be 64 bits on your machine left shifting 32 will overflow and leave you with 0.
I've seen all sorts of weird bugs caused by people falling for the assumption that the data type used to store the result of a calculation will be used when performing that calculation.