4 ms·
There's obviously many ways to avoid this situation, but it seems remiss not to mention in the "How to avoid this situation" section that you can usually malloc
by avar 7y ago
There's obviously many ways to avoid this situation, but it seems remiss not to mention in the "How to avoid this situation" section that you can usually malloc() such an array.
Obviously that's not a drop-in replacement in all cases, but once the article stats talking about API changes the obvious thing is to have a struct with (among other things) a pointer to such an array, have an my_init() function that returns a pointer to the struct which'll include a pointer to a malloc'd array, and a corresponding custom my_free() function to free the struct and its array(s).
This is the common way I've seen e.g. Pascal strings implemented in C. E.g. a struct with size_t alloc_pool, size_t strlen & char *str;
- saagarjha 7y agoYou don't even need malloc: just expose the address of the first element of the array (i.e. "erase" the size) instead of presenting the whole backing array, size and all. The issue here, of course, is that you can no longer use sizeof.
- jschwartzi 7y agoYeah, I'm really surprised that anyone would even use an array across object boundaries like this. I've never been in a situation where that would be preferable to providing a pointer and a size_t instead. It's been far more common throughout my career to do it that way instead of how the author is describing.
- klodolph 7y agoHow would you do that? The problem is that: extern int my_array[]; appears to expose only the address of the first element and not the size, but in fact the size is exposed through the linker.