3 ms·
The compiler cannot change the length field's size if a reference to the array (or a struct where it's contained) is ever passed to an unknown function, as that
by dzaima 2y ago
The compiler cannot change the length field's size if a reference to the array (or a struct where it's contained) is ever passed to an unknown function, as that function has to be able to read the length from memory based just on the spelled-out type.
Not a problem when passing the array by value (i.e. two registers of the data pointer and length), but then any packing automatically does not apply anyway.
- lisper 2y agoI don't understand this. Why does it matter if you're calling an unknown function? Why would an unknown function be unable to get the length? All you would need to do is to change the behavior of SIZEOF to make it aware of dynamically allocated arrays.
- dzaima 2y agoI mean in the case of an array type that tracks its length at runtime. Take: typedef struct { uint32_t arr1_len, arr2_len; int* arr1; int* arr2; } Foo; That's, on a 64-bit system, a 24-byte structure. Were it written as a struct of two array fields, the compiler couldn't choose a layout as efficient while maintaining being able to get a pointer to each field. Never mind that the compiler would likely not be omniscient enough to be able to tell that the structure is never used with arrays exceeding 2^32 elements. Perhaps you mean to keep using regular pointers for non-trivial heap-stored things, but I'd imagine that makes up a pretty significant amount of cases with buffer overflow potential.
- actionfromafar 2y agoOr add another sizeof keyword.