How to check a struct exists at a particular memory address?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri May 19 04:59:46 PDT 2017


On 5/18/17 4:20 PM, Gary Willoughby wrote:
> This might be a really silly question but:
>
> I've allocated some memory like this (Foo is a struct):
>
>     this._data = cast(Foo*) calloc(n, Foo.sizeof);
>
> How can I then later check that there is a valid Foo at `this._data` or
> `this._data + n`?

The correct way to do it is to make _data a slice:

Foo[] _data;
...
this._data = (cast(Foo*)calloc(n, Foo.sizeof)[0 .. n];

Note, you should also initialize the data, as calloc does not. This 
might work:

_data[] = Foo.init;

-Steve


More information about the Digitalmars-d-learn mailing list