quote:Original post by DrPizza
quote:The advantages are that you get to allocate an array on the stack even when you don''t know the size of the array until the function it is declared in is called. That''s obviously more efficient than allocating it on the heap.
If stack allocation is what''s wanted I feel that standardizing alloca() would be cleaner (as a library change I feel should generally be preferred to a language change, if possible).
I don''t see the issue with a language change that doesn''t invalidate existing code.
quote:
It also changes the way sizeof works in a pretty significant way; no longer is sizeof always evaluated at compile-time.
Is that likely to be a problem? Since the size of a VLA isn''t, by definition, known at compile-time, it''s quite obvious that sizeof won''t complete at compile-time. Are there any situations in which the fact that the size of a VLA isn''t known at compile-time would cause code to break?
quote:
quote:int calculate_something_destructive_nondestructively (const char *string) { char *local_copy[strlen(string)]; strcpy(local_copy, string); /* Do something */}
That code is wrong.
It ought to be { char local_copy[strlen(string) + 1]; }. No * (VLA declarations are written like normal automatic array declarations, and if you wanted to make a pointer to the array, you''d have to write char (*local_copy)[strlen(string) + 1]), and with room for the null.
Quite so. I was foolish enough not to test the code before posting it.
quote:
quote:Now, yes, in C++, you could use std::string or std::auto_ptr to avoid the hassle of having to deallocate the array. But, even then, that is inherently less efficient than using VLAs, because neither class allocates its memory on the stack.
AFAIK nowhere within the C99 standard does it say where the storage used by VLAs is located; VLA storage could in principle be located in some heap-like location with an automatic ''free'' call injected to handle tidy up; that would, I think, fulfil the demands of automatic storage duration.
Well, I don''t think the standard specifies the location for
any objects. Certainly, the word "stack" does not appear in the standard at any point.
But, VLAs
are defined to have automatic storage duration, and objects with that storage are typically expected to be allocated on the stack.
A possible implementation strategy would be to use alloca() for arrays under a certain size, and malloc() for other arrays.
The key distinction is that whilst it''s always possible that a VLA might not be allocated on the stack, it''s not
possible for a function to alloca() memory on the stack frame of the function that called it, including the std::string::string() function.