5 ms·
One example of undefined behavior is dereferencing a free'd pointer. How should that be defined?
by millstone 8y ago
One example of undefined behavior is dereferencing a free'd pointer. How should that be defined?
- taneq 8y agoIn a perfect world it would either be impossible by design or result in a compile error. I'd settle for "reliably crash with an error message saying where in the code it happened".
- bluecalm 8y agoYou can get it in C. Just set the pointer to NULL after free, you will get your crash, problem solved.
- taneq 8y agoTrue, you can even macro it for more convenience. I'm more worried about things where some obscure edge case causes the compiler to optimise away something important because it's deemed to be UB.
- lomnakkus 8y agoNo, you'll get UB.
- bluecalm 8y agoObviously you check for NULL first. If something may or may not exists you first ask if it exists (check for NULL) and then of it exists you do something with it. When you free something you destroy it, that's why it's useful to set the pointer which before pointed to it to NULL.
- lomnakkus 8y agoI just (well, a few days ago) explained to you that your suggested "solution" would result in UB. Then you come up with the "solution" that everybody must always check for NULL pointers before dereferencing them. If everybody always did that we might as well just define the behavior of reference-after-free, because what you said either a) requires you to keep a reference count (or null-check before every deref which may be even more expensive) at runtime(!), or b) requires a program-level proof. So... no. What you suggested is not a solution in any meaningful sense.
- gpderetta 8y agoHow would that work if you have two pointers pointing to the same object?
- clarry 8y agoI believe that would be impossible to implement without never reusing addresses or actually bolting on a GC. If you never reuse addresses, long running programs will have some trouble ahead. Oh, it's not even that simple because you'd have to make access to the region atomic.
- millstone 8y agoWhat language would you write this hypothetical GC in?
- ben-schaaf 8y agoInstead of defining what happens in the situation, most languages opt for making this type of error impossible in the first place. Languages with a GC do this by never freeing if a reference still exists. Rust (safe) does this by enforcing lifetimes at compile time.
- millstone 8y agoThese languages aren't capable of expressing the software that's routinely written in C (inc C++). For example, there's no way to enforce the lifetimes of NaN-boxed pointers managed by the multithreaded GC in the custom heap of your browser's JS engine. There's certain classes of C's UB that can be addressed, but most of it can never be without neutering C to the point of uselessness.