Pointers - Is it safe to point to invalid memory?
monkyyy
crazymonkyyy at gmail.com
Mon Aug 18 21:43:37 UTC 2025
On Monday, 18 August 2025 at 21:15:28 UTC, Steven Schveighoffer
wrote:
> On Monday, 18 August 2025 at 15:26:21 UTC, monkyyy wrote:
>> On Monday, 18 August 2025 at 07:32:13 UTC, Steven
>> Schveighoffer wrote:
>>> 2. You can store data in the lower bits of an aligned pointer
>>> (after all, this is just an interior pointer).
>>
>> Will the gc count this as a reference while scaning in any
>> case?
>
> As long as it's stored as a pointer, it is treated as a pointer.
>
> I'll try my hand at ascii art.
>
> Let's say you have an integer 0x4321 allocated in memory at
> address 0x100:
>
> ```
> -------------------------
> Address: | 100 | 101 | 102 | 103 |
> -------------------------
> Data: | 1 | 2 | 3 | 4 |
> -------------------------
> ```
>
> A pointer to the integer points at address 0x100
>
> ```
> -------------------------
> Address: | 100 | 101 | 102 | 103 |
> -------------------------
> Data: | 1 | 2 | 3 | 4 |
> -------------------------
> ^ ptr
> ```
>
> Now, you add a 1 to the pointer value to have it pointing at
> 0x101, it looks like this:
>
> ```
> -------------------------
> Address: | 100 | 101 | 102 | 103 |
> -------------------------
> Data: | 1 | 2 | 3 | 4 |
> -------------------------
> ^ ptr
> ```
>
> This is still pointing at the integer. So the GC believes the
> integer memory block is still valid because there's a pointer
> interior to the block
>
> Add 2, and you get a pointer to the `3` byte, add 3 and you get
> a pointer to the `4` byte. Add 4, and now it's pointing at the
> next integer, and so now it's no longer pointing at the
> integer, and this becomes invalid.
>
> So you have 2 bits of space you can use to store a value from 0
> to 3, and still have it be a valid pointer.
>
> -Steve
would this be .alignof or .sizeof?
https://dlang.org/spec/attribute.html#align
```d
struct S
{
align(default): // same as `align:`
byte a; // placed at offset 0
int b; // placed at offset 4
long c; // placed at offset 8
}
static assert(S.alignof == 8);
static assert(S.c.offsetof == 8);
static assert(S.sizeof == 16);
```
you make a big ol` struct with lets say like >5 members and you
got at least one int; could you start getting into the range 8
bits? maybe throw in an align on the struct?
Would there be a way to ask for an alignment that is bumped up to
the sizeof?
More information about the Digitalmars-d-learn
mailing list