Objective-C中的堆栈和堆地址

时间:2018-01-16 13:12:48

标签: objective-c memory stack heap

我在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 ?

1 个答案:

答案 0 :(得分:0)

无论块本地的哪个变量都存储在堆栈内存中,即使它是指针,但如果你使用指向存储地址的指针,并且该地址来自动态存储器而不是存储在堆内存中,例如:

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.   

}
相关问题