4 ms·
malloc() doesn't allocate arrays. It allocates blocks of memory. Hence sizeof doesn't work the same for malloc() objects as it does on arrays.
by kevin_thibedeau 4y ago
malloc() doesn't allocate arrays. It allocates blocks of memory. Hence sizeof doesn't work the same for malloc() objects as it does on arrays.
- int_19h 4y agosizeof doesn't work the same for malloc() because the type of the returned value is a pointer, and the behavior of sizeof is dependent solely on the static type. For comparison, calloc() is specifically defined as "allocates space for an array of ... objects" in the Standard, but since return type is still void*, the caveat with sizeof still applies.
- loeg 4y agoWell, sure, but the reason for that is that C's type system simply cannot represent functions returning arrays with known size. This is a weakness of the type system. Arrays degrade to a pointer type, lacking array length, as soon as you pass them between functions.
- kevin_thibedeau 4y agocalloc() doesn't allocate an array either. It's purpose is to allocate blocks of memory larger than SIZE_MAX. Mostly irrelevant now but was an issue on 16-bit systems.
- int_19h 4y agoI literally quoted the Standard (C17 7.22.3.2) in my earlier comment, and it very specifically says that calloc allocates an array. This language isn't from a new standard, either - it goes all the way back to ISO C90.
- fsckboy 4y ago> sizeof is dependent solely on the static type so what, an array has a size that sizeof can measure. what is returned from malloc is not an array and what sizeof measures is not reflective of the size of the allocation
- unwind 4y agoThat is not true, as long as VLA:s are in the language spec for the version you're using. This works: void vla_print(int n) { int foo[n]; printf("Got %zu bytes right there!\n", sizeof foo); } int main(void) { vla_print(47); return 0; } This prints 188 [1]. Even if you "hide" n from the compiler, i.e. make its value something that is only known at run-time (which is jumping through hoops, pretty sure the above is enough). Also, it was jarring that the fine article kept referring to sizeof as sizeof(), a notation that C programmers typically use to identify function names. As everyone knows, sizeof is not a function. It's an operator. I really need to print up that t-shirt soon. Or maybe my first tattoo ... Hm. [1]: https://ideone.com/kKf3bT https://ideone.com/kKf3bT
- int_19h 4y agoIn your example, sizeof works because the type of foo is int[n], so I'm not sure what point you're making. It's still true that the way sizeof works depends solely on the static type of the expression that it is applied to - if it's an array, you get the actual size, including the necessary dynamic computation if it's a VLA, and if it's a pointer, you get the size of a pointer even if it points to an array.