-2

I've been reading about sizeof, malloc, and malloc_size, but for some reason I cannot get it to work properly in objective c.

What I'm trying to do is to dynamically allocate memory and then check the size of the pointer.

I tried doing this:

void *pointer = malloc( sizeof(void) * 8 );
long test1 = malloc_size(pointer); // Its value is 16
long test2 = sizeof(pointer); // Its value is 8

The link below answer exactly the same question but it doesn't work for me.

EDIT: I also tried using

char *malloc( sizeof(char) * 8)

but it didn't work either.

Diego A. Rincon
  • 747
  • 1
  • 8
  • 25
  • `sizeof(void)` doesn't really make sense. See here: http://stackoverflow.com/questions/1666224/what-is-the-size-of-void – MatthewD Jun 14 '13 at 08:14
  • sizeof(void) is returning the same value as sizeof(char), which is 1. It doesn't generate any compilation errors nor warnings. – Diego A. Rincon Jun 14 '13 at 08:31
  • It's compiler-specific behaviour. GCC returns 1, but Visual C++ 2012 returns 0 and gives a compiler warning. See here: http://msdn.microsoft.com/en-au/library/tf66xte5.aspx – MatthewD Jun 15 '13 at 05:11

2 Answers2

1

malloc_size is returning the correct answer - malloc returns a block of at least the size you request, but it may be (a little) larger. This is just a facet of the way dynamic memory is managed, it parallels the way disk files are made up of allocation blocks. A quick test on 64-bit Intel suggests malloc's allocation unit is probably 16 bytes.

CRD
  • 52,522
  • 5
  • 70
  • 86
0

pointer is of type of *, so no matter what memory is malloced to pointer, sizeof(pointer) should be fixed value, it's 4 (32bit sys) or 8 (64bit sys).

TieDad
  • 9,143
  • 5
  • 32
  • 58