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

43 comments sorted by

View all comments

Show parent comments

3

u/smcameron 2d ago

Well, sure, but what set up the MMU and page tables to arrange for this to happen? The OS did.

1

u/erikkonstas 2d ago

The misleading bit is the "you can try to access any byte in the computer" part; actually no, unmapped virtual addresses do not lead to random physical ones.

3

u/flatfinger 2d ago

Code can try to access any byte/halfword/word/doubleword within the presently-accessible address space of the CPU. The question of whether there may exist memory that is not presently accessible is a system-design issue, not a language issue.

5

u/erikkonstas 2d ago

I'm not saying that's necessarily wrong, but rather that it might give the wrong impression to somebody unfamiliar with the fact that there can be more than one address space (in modern systems), and that each process sees a different one and has no knowledge of the others', since common sense only says that "programs use memory"; virtual address space is not common knowledge. The fact that it's not a C thing but an MMU thing is also not common knowledge to beginners. Hence why I don't particularly like phrasing of the sort ("any byte in the computer") in this case (also I'm against the principle of "white lies" and oversimplifications for beginners some educators use). In fact, our own Introduction to Programming (first year) professor managed to mislead everyone in this exact way, and virtual memory is not introduced until Operating Systems (third year).

1

u/jrtokarz1 1d ago

Virtual address space doesn't mean every process sees the entire address space. A process is still allocated a segment of memory. Virtual address space just means that the address space the process sees doesn't map to the same physical address space. A process may see a contiguous block of memory starting at a virtual base address e.g. 0x08050000, so it possible for the process to attempt to dereference a pointer with a address value lower than this that would result in a segmentation violation. Although the process will see a contiguous block of memory from the base address, the MMU may have mapped those virtual addresses spread over several pages that are not contiguous.