what is the different with malloc_size and sizeof

2019-08-08 19:37发布

I am using Ojb-c, and I want to know the memory size of an object, but I got this,

NSObject *obj = [[[NSObject alloc] init] autorelease];

NSLog(@"malloc size of myObject: %zd", malloc_size(obj));
NSLog(@"size of myObject: %zd", sizeof(obj));

  malloc size of myObject: 16
  size of myObject: 4

I know the sizeof(obj) is 4, because the pointer size on ios 32 is 4 bytes, what is the difference?

But more than this,

@interface TestObj : NSObject

@property (nonatomic, retain) NSArray *arr;
@property (nonatomic, assign) int count;

@end

@implementation TestObj

@end


    TestObj *obj2 = [[[TestObj alloc] init] autorelease];

    NSLog(@"malloc size of obj2: %zd", malloc_size(obj2));
    NSLog(@"size of obj2: %zd", sizeof(obj2));

  malloc size of obj2: 16
  size of obj2: 4

how could I know the real size of TestObj ? thanks.

2条回答
何必那么认真
2楼-- · 2019-08-08 20:05

The sizeof the object is how much space it requires for that object to be stored in memory. The malloc_size is how much space was actually allocated for it (for example, in a memory allocation system with fixed-size pools, you might be allocated a different amount depending on how much other memory was in use).

查看更多
冷血范
3楼-- · 2019-08-08 20:06

sizeof() is a compile-time measurement. Note that sizeof(obj) in your example is telling you the size of the pointer variable, not the size of the object it points to. Note that the size of an Objective-C object is not known at compile time, so sizeof will not work for them.

malloc_size() is a runtime measurement. It tells you the size of a block allocated with malloc. Note that malloc often rounds up, so this size may be larger than necessary. Note that some objects are not allocated with malloc so malloc_size() will return zero.

查看更多
登录 后发表回答