0
votes

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
4
Please tag this Objective C and not C.Lundin

4 Answers

3
votes

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?

1
votes

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

1
votes

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.

0
votes

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