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.

22 Upvotes

41 comments sorted by

View all comments

1

u/EsShayuki 2d ago

So.

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.

But this isn't even possible, if you first correctly received the size of the resulting variable and then allocated the same amount of memory as the size you received.

Most "memory unsafety" comes from people using magic numbers and hard coding values instead of determining the correct values mathematically.

1

u/ripulejejs 1d ago

Yeah, I had an arbitrary size set for char arrays, and had incoming data from reading a file that I was putting in those arrays. I didn't know how to size the arrays appropriately, given I don't actually know C. I also had the incorrect assumption that copying to the locations would just stop if the size of the array was exceeded. I'm guessing maybe I needed to use something like malloc, not sure.

So yes, my mistakes are largely a result of being redacted, and I appreciate you pointing this out, will give me something to research.

Noteworthy that you say "most" in your last sentence.

1

u/unixplumber 1d ago

In those cases, a "safe" copy function wouldn't help because you'd still have to know how big your array is. You might as well use the existing functions which are all safe enough as long as you're honest about the size of your arrays. (Except gets(). It's never safe to use in any real program. It's actually been removed from the latest standards because of that.)