8 ms·
> Why is C unsafe? Mostly memory. C can't even do all of integral arithmetic safely. It's a language that goes really out of its way to add unsafety.
by marcosdumay 3y ago
> Why is C unsafe? Mostly memory.
C can't even do all of integral arithmetic safely. It's a language that goes really out of its way to add unsafety.
- jstimpfle 3y ago[flagged]
- JonChesterfield 3y agoPost might have signed integer overflow => undefined behaviour => delete all the code in mind. Which can be avoided if you remember that hazard is there. What's integer divide by zero in C? Would you consider that safe?
- jstimpfle 3y ago[flagged]
- JonChesterfield 3y agoDecent chance integer divide by zero will kill your process. Might even call it a floating point exception. Maybe that qualifies as safe to you, seems not-safe to me. Compelling alternative would be for it to return zero. Which is safe. But C doesn't do that. So you have to remember to never write '/', and instead call my_divide, which has a branch in it.
- jstimpfle 3y ago> Compelling alternative would be for it to return zero. Which is safe. Is it? Or is it just another opportunity for a bug to hide?
- jovial_cavalier 3y ago>Compelling alternative would be for it to return zero. That's actually way less safe than crashing. If your code doesn't handle the case where the denominator is zero, it is likely that the logic around your division doesn't consider it either. The behavior you suggest would take a rapidly increasing number and instantaneously set it to 0, then silently pass it into the logic that was humming along up to that point. Since there's no symbol for NaN in integers, there is no safe way to represent `x / 0`, and thus the best way to handle it is to fault. Even better would be if the compiler caught it and warned you.
- jstimpfle 3y ago> Even better would be if the compiler caught it and warned you Which is probably what the big compilers do (seems reasonable to expect it) -- I can't really know though because the last time I've written code that divides by 0 in an easily provable way is probably a long time ago.
- TazeTSchnitzel 3y ago> Which can be avoided if you remember that hazard is there. This is true, but it could be argued that it's harder to avoid signed integer overflow in C/C++ than it is to avoid buffer overflows: you often don't know what types you're working with, due to the usual arithmetic conversions and integer promotions, and checking whether an overflow will occur without causing an overflow is difficult in itself. It's kind of uniquely awful in this respect, basically every other popular language has a more practical integer programming model.
- celrod 3y agoI like integer overflow being UB. Makes it easier to check for by enabling a sanitizer. With it being defined as wrapping, it would be illegal for overflow to cause a runtime trap. Of course, rust mandates the trap on debug builds, which is a fine approach too.
- rewmie 3y ago> What's integer divide by zero in C? It's explicitly left undefined. > Would you consider that safe? Yes, because, as all C newbies can easily explain to you, the general rule of thumb is that undefined behavior should be treated as a fault and thus should be handled as a bug. Hence, your question reads as "Would you consider a bug to be safe?". In case of integer division, you simply need to check that the divisor is not zero prior to executing the division. Done.
- JonChesterfield 3y agoPeople new to C hear about UB, resolve to not do that, and that seems fine. People not new to C have noticed that so many constructs are UB as to make it infeasible in practice that any given codebase will be free of UB. What makes C a fundamentally unsafe language is that conceptually minor errors have unspecified consequences of unbounded magnitude, limited to no compile time detection of said errors, and that even builtins like + are specified to compile successfully into nonsense in some contexts. Integer operations can be defined to be safe. Whatever integers you pass to your maths operation, you get an unsurprising integer back. What the language does in the presence of your bug is definitely part of the safety properties of the language.
- jstimpfle 3y ago> What makes C a fundamentally unsafe language is that conceptually minor errors have conceptually unspecified consequences of unbounded magnitude. There, fixed that for you. Everybody knows that these scary stories can happen (even though almost nobody has seen them happen in the wild). But for the most part they should be seen as a combination of (typically, obviously) buggy code and compiler optimizer defects, rather than fundamental defects of the language. > Integer operations can be defined to be safe. Whatever integers you pass to your maths operation, you get an unsurprising integer back. There is at least 1 arithmetics teacher disagreeing with you. There is no point, and let me scream again NO FR**G POINT, for a zero divide to return zero. I want it to crash. And I consider it a compiler defect if the compiler proves that a zero division is happening and proceeds to do a strange optimization instead of reporting it. It's a fine line to walk though, since there is also the case of legitimately assuming that it doesn't happen, and not emitting the code that triggers the crash. There probably should be compiler knobs to tune the behaviour.
- shadowgovt 3y agoAccurate comment of the day. C intentionally leaves behavior undefined to allow flexibility in implementation, which allows implementations to take advantage of optimizations that other languages can't because they are over-constrained for the target architecture. What's the order of operations for sequence of expressions added together? Do they evaluate left to right or right to left? The answer is, very intentionally, "any order is allowed and order may change between executions of a line." This makes it possible to make C implementations equivalently fast on various architectures where, for example, stacks and stack operation ordering make it more efficient to do one or the other. Hell, the language is even usable in an architecture where each of those expressions could be run purely parallel. Of course, the downside is that you definitely can't assume side effects caused by the left side of an expression occurred before the right side. But the trade-off is that you do have to be extremely sensitive to making assumptions that the specification doesn't actually specify, or you are going to trip over an error in your assumptions that matters on your implementation. The actual "this is undefined behavior so the program deleted your whole hard drive" scenario is incredibly unlikely on a modern desktop or server architecture, but the languages flexibility does mean that you're perpetually one missed trick away from incredibly perplexing behavior. This is a feature of the language not a bug. It's how the language gets you as close as it possibly can to the speed you would be able to get hand writing the assembly at every step of the process.
- AlotOfReading 3y agoIt's not a bug only in the sense that it's intentional. It's certainly not "good" or a feature any other language should ever copy again because it prevents you from saying anything formally about the properties of the system at time T, when UB has occurred or will occur at any point along the execution path. As a result, you're always stuck with the qualification that x is true in the absence of UB, something that no automated checker can ever verify and careful review is insufficient to validate in the real world. Whether or not this is a common issue on commodity hardware is basically irrelevant given C's remaining niche. It's mainly the language of kernels, drivers, and firmware nowadays, not primitive CLI tools that can crash whenever they feel like it. Ensuring system state with high reliability is the raison d'etre of modern C, so the lack of ways to do that without significant caveats is incredibly problematic.
- diogenes4 3y agoIntegers are an abstraction on top of words; words are perfectly safe.
- rewmie 3y ago> C can't even do all of integral arithmetic safely. Your comment reads like nonsense. Are you able to provide what you feel is the best example that substantiates your claim?
- aidenn0 3y agoSigned integer overflow is UB in C.
- matheusmoreira 3y agoCan't we force the compiler to define the behavior with flags like -fwrapv? I use them as a matter of course. Also use -fno-strict-aliasing.
- Chabsff 3y agoYes, you can tell the compiler to generate predictably-behaving output for non-compliant code. However, that code is not valid C anymore, but a dialect. Since this is a discussion about what C is and is not, I think it's fair to limit ourselves to the actual language as-is.
- matheusmoreira 3y ago> that code is not valid C anymore, but a dialect > I think it's fair to limit ourselves to the actual language as-is I don't agree. Standard C only ever seems to be discussed when some asinine undefined behavior starts causing problems that we have to work around. No one cares about it otherwise. It's better to redefine C as whatever the compilers accept. Now we can actually move forward and actually fix problems such as "signed integer overflow is undefined" -- just tell the compilers to start dealing with it.
- aidenn0 3y agoCompilers are typically benchmarked with ubsan and friends turned off, so when we say "C is fast" [with undefined behavior enabled] and "C is reasonably safe" [with undefined behavior defined] we aren't talking about the same language.
- bensecure 3y agoI'm pretty sure that this is one of the unsafeties that rust borrows from c, even as it attempts to eliminate all the others. Checking every addition adds a massive slowdown, without giving much useful protection against vulns or corruption.
- Hirrolot 3y ago> I'm pretty sure that this is one of the unsafeties that rust borrows from c But integer arithmetic is safe in terms of Rust. > Checking every addition adds a massive slowdown It only does so for debug mode. In release mode, it uses modular arithmetic.
- xscott 3y agoLol, when C does it, it's "unsafe". When Rust does it, it's "modular"!
- deleted 3y ago[deleted]
- mathiaskindberg 3y agoFor anyone wondering about the term "modular": > In mathematics, modular arithmetic is a system of arithmetic for integers, where numbers "wrap around" when reaching a certain value, called the modulus. The modern approach to modular arithmetic was developed by Carl Friedrich Gauss in his book Disquisitiones Arithmeticae, published in 1801. https://en.wikipedia.org/wiki/Modular_arithmetic https://en.wikipedia.org/wiki/Modular_arithmetic
- nuancebydefault 3y agoModular/modulus (and also twos complement) is a natural feature of most CPUs. It comes natural by the way logic counters work in hardware. C enforces that by not touching that logic. Rust is the same in that respect. Python on the other hand treats integers as objects with a virtually unlimited amount of digits. That said, float/double precision and logic is still CPU dependent and is used as-is for most languages.
- theamk 3y agoC is a low level language, so when programmer writes "+" they get "ADD" opcode. That's what "low level" means. If one wants "+" to add then do range checks, they can use a higher level programming language (or a special function, perhaps an intrinsic, in C)
- monocasa 3y agoThere's plenty of cases in C where the use of a + operator doesn't result in any form of add instruction being emitted.
- shrimp_emoji 3y agoBut 53 years later, it's added the `<stdckdint.h>` header, offering `ckd_add()` and friends. :D Better late than never!