malloc in C: same sizeof before and after?
Because sizeof
is evaluated at compile time and yields the size of the type of set
, a pointer to int
.
There is no generic way to measure the size of memory pointed to by a pointer in C, other than the special case that strings are null terminated by convention.
sizeof
will yield the size of the pointer (4 bytes on a 32-bit system, 8 bytes on a 64-bit system), not of the memory pointed to.
If you want to track the size of memory allocated, options are:
- Track it in a separate variable
- Introduce a special array terminator (for example, the minimum or maximum value of
int
if your application will never validly use that value. - Use an alternate memory management library (for dmalloc has dmalloc_examine, which will return the size of memory pointed to). These should drop right in with minimal or no code changes, except for where you want to use their expanded memory API.
The item you're measuring, set
, is a pointer-to-integer ( int*
).
And a pointer-to-integer is 4-bytes.
sizeof
does NOT measure the amount of memory allocated to the pointer.
It only measures the "item" itself (in this case, a pointer).