0

I'm having a issue getting the size of a struct pointer after allocating the memory using malloc or realloc. I've worked around this by keeping track of the memory in a separate counter, but I would like to know if this is a bug or if there is a way to properly query the size of a struct pointer.

Sample code demonstrates that no matter how much memory I allocate to the struct pointer it always returns 4 when querying using the sizeof() method.

typedef struct {
    int modelID;
    int bufferPosition;
    int bufferSize;
} Model;

Model *models = malloc(10000 * sizeof(Model));

NSLog(@"sizeof(models) = %lu", sizeof(models)); //this prints: sizeof(models) = 4
robhasacamera
  • 2,967
  • 2
  • 28
  • 41

4 Answers4

3

4 is the correct answer, because "models" is a pointer, and pointers are 4 bytes. You will not be able to find the length of an array this way. Any reason you're not using NSArray?

edsko
  • 1,628
  • 12
  • 19
1

4 is the correct answer. Pointers point to a memory location which could contain anything. When you are querying the size of a pointer, it gives the size of the memory location which holds the pointer, which in your case is 4.

For example

int *a = pointing to some large number;

int *b = pointing to a single digit number;

In the above case, both a and b have the same size irrespective of where they are pointing to.

For more information, have a look at this post size of a pointer

Community
  • 1
  • 1
krammer
  • 2,598
  • 2
  • 25
  • 46
1

If I understand you correctly you want to get at the size of the allocated buffer.

sizeof if the wrong way to go since it is evaluated at compile time. The size of the buffer is a runtime concept.

You would need a way to query you C library to return the allocation size for the pointer to the buffer.

Some systems have a way to get that kind of information, for instance malloc_size on Mac OS.

Nikolai Ruhe
  • 81,520
  • 17
  • 180
  • 200
  • This is exactly what I was looking for. To get it to work for iOS I had to import malloc/malloc.h, after that it all seems to be working now. Thank you. – robhasacamera Oct 25 '11 at 08:52
0

sizeof(myvar) will return size of pointer. in 32bit environment it equals to 4(bytes). why don't you use sizeof (Model) instead?

heximal
  • 10,327
  • 5
  • 46
  • 69