testing if data is allocated on the stack or heap

drug drug2004 at bk.ru
Tue Oct 17 17:41:22 UTC 2017


17.10.2017 20:27, Biotronic пишет:
> module stackCheck;
> 
> private size_t stackStart;
> enum size_t pageSize = 0x1000;
> 
> static this() {
>      import core.stdc.stdlib : alloca;
>      stackStart = cast(size_t)alloca(size_t.sizeof) & ~(pageSize-1);
> }
> 
> bool onStack(void* p) {
>      size_t end = (cast(size_t)&p & ~(pageSize-1)) + pageSize;
>      size_t pp = cast(size_t)p;
> 
>      if (end > stackStart) {
>          return pp >= stackStart && pp <= end;
>      } else {
>          return pp <= stackStart && pp >= end;
>      }
> }
> 
> bool onStack(T)(ref T p) {
>      return (&p).onStack;
> }
> 
> unittest {
>      int n;
>      int* p = new int;
> 
>      assert(n.onStack);
>      assert(!p.onStack);
> }

Thanks! Your solution not only works but is portable also.


More information about the Digitalmars-d-learn mailing list