Leaving a pointer to it on the stack
Adam D. Ruppe
destructionator at gmail.com
Thu Aug 13 20:08:06 UTC 2020
On Thursday, 13 August 2020 at 20:04:59 UTC, Andre Pany wrote:
> Hi,
>
> in the specification
> https://dlang.org/spec/interfaceToC.html#storage_allocation
> there is this paragraph:
> "Leaving a pointer to it on the stack (as a parameter or
> automatic variable), as the garbage collector will scan the
> stack."
>
> I have some trouble to understand what does this mean. Given
> this example:
>
> ```
> import std;
>
> void main()
> {
> int* i;
> sample(&i);
> writeln(*i);
> }
>
> extern(C) export void sample(int** i)
> {
> *i = new int();
> **i = 42;
> }
> ```
>
> Int variable is created on the heap. How do I leave a pointer
> on the stack?
You just did - the `int* i` is a pointer left on the stack for
the duration of `main` so the GC won't collect it until after
main returns.
But after main returns, even if `sample` kept a copy of it
somewhere in some other location, the GC might reap it...
More information about the Digitalmars-d-learn
mailing list