Pointers - Is it safe to point to invalid memory?

Steven Schveighoffer schveiguy at gmail.com
Mon Aug 18 07:32:13 UTC 2025


On Saturday, 16 August 2025 at 22:00:25 UTC, monkyyy wrote:

> Its over in the gc that has any relivence:
>
> https://dlang.org/spec/garbage.html#pointers_and_gc

This list is really mostly based on a hope that at some point D 
will have a moving GC. This is never going to happen. Not only 
that, but we should not be using the term Undefined Behavior for 
many of these problems, as they are library specific. UB has a 
special meaning when it comes to a programming language.

My set of rules about the GC:

1. You can store a pointer as an integer as long as there is 
still a pointer somewhere that keeps the memory from becoming 
garbage. Storing a unique referencing pointer *solely* as an 
integer type is UB (this can be collected at any time, resulting 
in use-after-free).
2. You can store data in the lower bits of an aligned pointer 
(after all, this is just an interior pointer).
3. You can store any value as a pointer, even one that points at 
GC data.
4. Dereferencing a pointer to a valid GC allocated block that was 
provided by a GC function or an interior pointer from that GC 
request is fine.
5. Dereferencing a pointer that did not come from a GC function, 
but points at a valid GC block should only be done by the GC. But 
for purposes of the language, this is defined behavior.
6. Creating pointers that point at the end of a GC block is 
allowed. Dereferencing them is not. Dereferencing pointers 
derived from such pointers (e.g. by subtracting an offset) is 
also not allowed.

I'll try at dconf to get agreement on updating this list in the 
spec.

-Steve




More information about the Digitalmars-d-learn mailing list