【问题标题】:Stack and Heap addresses in Objective-CObjective-C 中的堆栈和堆地址
【发布时间】:2018-06-25 05:05:59
【问题描述】:

我对 Objective-C 中的内存分配进行了大量研究,并且阅读了很多关于这些内容的文章和博客,但我仍有一些不清楚的地方。我知道对象类型存储在堆中,原始类型存储在堆栈中,但是请您向我解释一下关于列出的示例的更多信息:

NSObject *obj;

NSLog(@"%p", obj); //prints 0x0 which means address in stack ?
NSLog(@"%p", &obj); //prints 0x7ffee427bf68 which means address in heap ?

obj = [[NSObject alloc] init];

NSLog(@"%p", obj); //prints 0x6000000119b0 which means address in stack ?
NSLog(@"%p", &obj); //prints 0x7ffee427bf68 which means address in heap ?

原始类型也一样:

int value = 23;

NSLog(@"%p", value); //prints 0x17 - is that a stack address ?
NSLog(@"%p", &value); //prints 0x7ffeea19bf6c - is that a stack address too ?

【问题讨论】:

  • 0x17 是十六进制的 23。这是一个值,而不是地址。
  • 真的……我以前没有意识到原始类型。谢谢你的澄清:)

标签: objective-c memory heap-memory stack-memory


【解决方案1】:

块本地的任何变量都将存储在堆栈内存中,即使它是指针,但如果您使用指针来存储地址并且该地址来自动态内存,那么它将存储在堆内存中,例如:

Func()
{
int *a ;    
int b;   --stack memory
a = malloc (sizeof(int));    
Printf &a;-----this will be stack memory pointer and will be store in stack memory.   
Print a;-----this will point to address which is allocate by heap this will be store in heap memory.   

}

【讨论】:

    猜你喜欢
    • 2011-04-01
    • 2023-03-20
    • 2012-04-26
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多