On Tuesday, 17 October 2017 at 15:33:02 UTC, drug wrote:
My code fails and I guess the reason is I have a slice to data in the stack and it becomes garbage in some moment. So I need a way to check where data is placed. Is it right that it can be done in linux using `sbrk` so that if the addr of data is less than `sbrk(0)` returning then data is on the stack and on the heap in other case?

I have very little knowledge about sbrk, so here's my solution.

Tested on win32 and win64.

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);
}

--
  Biotronic

Reply via email to