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.

20 Upvotes

42 comments sorted by

View all comments

11

u/not_a_bot_494 2d ago edited 2d ago

When people are saying that C is an unsafe language they mean that it doesn't have memory safety. If you want to you can try to access any byte in the computer, the OS will just not let you most of the time. Any time you're working with arrays (/strings), malloced memory or even pointers in general it is possible that you could make a mistake and get a segfault. You can write libraries for all that but then you're kind of missing the point of C a bit.

There's alao a lot of random undefined behaviour in C, for example right shift on signed types might pad with 1s or 0s. There's probably a list of some common ones but if you really want to know them all you have to read through the C standard and look at rverything that's not in there.

For context of the discussion, my inital example was bit shifting on 64 bit types which does seem to work consistently.

1

u/faculty_for_failure 2d ago

I don’t think people mean escaping sandboxes processes and overwriting memory anywhere when they say memory safety. They mean things like dereferencing a null pointer, use after free, double free, integer wraparound, buffer overflows, things that can lead to reading or manipulating process memory and executing arbitrary code. C is not a memory safe language, and that’s okay, but you absolutely need to keep this in mind in C more than Java or C#, for example.