How to tell if something is heap or stack allocated?

后端 未结 1 1263
再見小時候
再見小時候 2021-01-17 18:16

I wonder if there\'s a way to figure out if a variable is stack or heap allocated.

Consider this:

struct SomeStruct;

fn main() {
    let some_thing          


        
相关标签:
1条回答
  • 2021-01-17 18:54

    If you're on some POSIX system, you can probably use the sbrk() system call with an argument of 0 to determine the current location of the program break, which is the current limit of the heap. If the address of a given value is less than this address but greater than the start of the heap then it's on the heap. I don't know how you'd check if it's on the stack though, which isn't necessarily automatically the alternative of not being on the heap, since it can also be statically initialized or uninitialized data, though that would probably be obvious to you upon inspection of the code. You can probably use the rbp register on an x86_64 architecture, which should point to the beginning of the current stack frame. That's if you want to check if it's on the current stack frame, or if you want to check if it's anywhere on the stack you can probably use rsp.

    I think you can get the start of the heap with the end() system call using the end argument. So the lower bound of the heap would be the result of end(end) and the upper bound would be sbrk(0).

    0 讨论(0)
提交回复
热议问题