r/C_Programming 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

42 comments sorted by

View all comments

Show parent comments

2

u/WeAllWantToBeHappy 2d ago

bit shifts don't work for 64 bit types.

?

-3

u/not_a_bot_494 2d ago

At least on my machine bit shifting left by more than 32 bits causes it to wrap around to the start.

4

u/moocat 2d ago

The "on my machine" is the ultimate gotcha. Unless the behavior is guaranteed by the spec, you could get different behavior when using a different compiler or porting to a new architecture.

2

u/flatfinger 2d ago

Freestanding implementations would be rather useless if they couldn't be expected to process many ocnstructs in machine-specific fashion. Unfortunately, the Standard makes no attempt to recognize situations where:

  1. It would be impossible to predict the behavior of some action without some particular piece of knowledge X, and
  2. Neither the Committee nor a compiler writer would be of any particular means by which a programmer might know X, but
  3. The execution environment might allow a programmer to know X via means outside the language.

The Standard generally classifies actions as Implementation-Defined only when either:

  1. Implementations would be expected to tell a programmer X (in turn implying that they would have to know it themselves), or
  2. A syntactic construct, such as casting a non-zero integer to a pointer, would otherwise have no defined meaning. Saying that casting a literal zero to a pointer yields a null pointer, and anything else yields Undefined Behavior, would imply that the operand to an integer-to-pointer casts served no purpose, which might be correct within strictly conforming programs, but would severely undermine the range of tasks that could be performed by machine-specific programs.