-2

Possible Duplicate:
determine size of dynamically allocated memory in c

I have a struct in my c code, but this question is also valid for all other types so I will use int instead of struct I created.

int *a = realloc(NULL, 10*sizeof(int) );
printf("%d\n",sizeof(a)); //prints 4, needed to be 40

int b[10];
printf("%d\n",sizeof(b)); //prints 40

My question is this: I am using realloc in my code and I don't know how I can find the total size of my array. What is the easiest way to do that? Thank you.

Community
  • 1
  • 1
ibrahim
  • 3,254
  • 7
  • 42
  • 56

4 Answers4

1

Remember that sizeof is evaluated at compile-time (except with VLA, but it's not your case). Imagine that you take the size of realloc argument as user's input : it's impossible to the compiler to know the real allocated size. So it returns the size of the pointer.

md5
  • 23,373
  • 3
  • 44
  • 93
  • "evaluated at compile-time" - not true for C99 apparently, where sizeof works with VLAs at run-time (I learned something new today !). – Paul R Jul 23 '12 at 10:16
  • I understood. So is there any function that can calculate its size dynamically or should I keep its size in a variable? – ibrahim Jul 23 '12 at 10:17
  • You need to track allocation sizes yourself - there is no portable way of getting this information after the fact. – Paul R Jul 23 '12 at 10:19
  • @Paul R : Yes, C99's VLA are an exception : but it's a very strange subject and sometimes a bad thing (there are optionnal with C11, so I don't use them at all... Almost deprecied...). – md5 Jul 23 '12 at 10:22
  • @ibrahim : There is no portable way to get this size. Store your size into a data structure, it's the better way ! – md5 Jul 23 '12 at 10:23
0

In short it's something that you'll need to store in your code, and pass around to your various functions. Since you passed that information into realloc it's available already.

Also remember that sizeof won't work on pointers, it only will return the size of the pointer, not the size of the memory that the pointer points at.

display101
  • 2,035
  • 1
  • 14
  • 10
0

from http://en.wikipedia.org/wiki/Sizeof

In the programming languages C and C++, the unary operator sizeof
is used to calculate the size of any datatype, measured in the
number of bytes required to represent the type.

This means that this

sizeof( int* )

returns size of pointer on your architecture. And if you want to know the size of your array, you have to do:

sizeof( your_type ) * array_size
René Kolařík
  • 1,244
  • 1
  • 10
  • 18
0

sizeof(a) returns the size of the pointer not what it points to. You have to keep track of that yourself if you allocate memory with malloc or realloc.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621