如何判断是分配堆还是堆栈? [英] How to tell if something is heap or stack allocated?

查看:71
本文介绍了如何判断是分配堆还是堆栈?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种方法可以确定变量是堆栈还是堆分配的.

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

考虑一下:

struct SomeStruct;

fn main() {
    let some_thing = Box::new(SomeStruct);
    println!("{:p}", some_thing);
    foo(&*some_thing);
}

fn foo (bar: &SomeStruct) {
    println!("{:p}", bar);
}

打印

0x1
0x1

然后

struct SomeStruct;

fn main() {
    let some_thing = &SomeStruct;
    println!("{:p}", some_thing);
    foo(some_thing);
}

fn foo (bar: &SomeStruct) {
    println!("{:p}", bar);
}

打印

0x10694dcc0
0x10694dcc0

我可以看到堆分配版本的内存地址要短得多,但是我不知道这是否是一种可靠的方式来区别.我想知道是否有类似 std :: foo :: is_heap_allocated()

I can see that the memory address is much shorter for the heap allocated version but I don't know if that's an reliable way to tell the difference. I wonder if there's something like std::foo::is_heap_allocated()

推荐答案

如果您使用的是POSIX系统,则可以使用

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.

我认为您可以使用 end 参数> end() 系统调用.因此,堆的下限将是 end(end)的结果,上限将是 sbrk(0).

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).

这篇关于如何判断是分配堆还是堆栈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆