I have an integer array that's only useful in a single code block. I'd like to declare it and initialise it to zero on the stack to avoid the overhead of the heap.
I'd like to do this dynamically and initialise every index to zero. Basically, I'd like a stack version of calloc
!
Is this possible?
Variable length arrays (VLA) are typically allocated on the stack. However, as they have their size decided in run-time, you cannot provide an initializer to them. This could be solved with a separate call to memset
.
void func (size_t n)
{
int array[n];
memset(array, 0, sizeof(array));
...
}
However, declaring arrays like this on the stack isn't really recommended practice in many situations. You'll have to ensure that the size is within some reasonable limits or you'll get stack overflow. calloc()
+ free()
at the end is slower but safer in that regard.
Yet another option is static storage duration:
void func (size_t n)
{
static int array[MAX];
memset(array, 0, sizeof(int[n]));
...
/* only use up to n items of the array */
}
This has the advantage of being fast and safe from stack overflows both. The disadvantages is that you have to pre-allocate the whole array, as well as thread safety concerns.
But please note that no matter which method you pick, you will reasonably have to design the code to work up to a "MAX" limit. Since a computer with unlimited memory will never exist. So it isn't correct to say that the static
version consumes extra memory needlessly - it consumes enough memory to handle the worst-case scenario of your application. A stack or heap version which need to handle the same scenario will have to consume just as much memory under the worst-case scenario, though in that case only during a limited time.