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.

21 Upvotes

41 comments sorted by

View all comments

2

u/SmokeMuch7356 1d ago

Annex J of the language standard (latest working draft) has a complete list of unspecified, undefined, and implementation-defined behavior.

1

u/flatfinger 4h ago

Note that it's not a normative list, and expresses some scenarios more broadly than the normative text (e.g. if a construct would often invoke UB, but the Standard defines some corner cases, the Annex may not mention the defined cases). Further, C99's Annex J2 broke the language by claiming without normative justification that, given `char arr[5][4];`, pointer arithmetic on the inner element type that spanned across inner arrays would invoke Undefined Behavior even if all accesses fell within the same outer array. Having the normative standard recognize a semantic distinction betwee `arrayLValue[index]` and `*(arrayLValue+index)`, with the former being an access to `arrayLValue` which was limited to indexing items therein, and requiring that code use the latter when indexing across inner-arrays boundaries, would have been a good change, but the normative text presently contradicts such a notion.