Reputation: 249
I have a situation where I'd really, really like to use an array with the static storage keyword, but allocate it dynamically. I'm using this array as a buffer to read some output into and I don't want to reallocate every time because the function is going to run many times a second and needs to be fast. I also want the size to be dynamic because the size of the output varies based on user configuration. My understanding is that this isn't possible in C. Does anyone know a good workaround?
I've thought about dropping static and using malloc wrapped in a null check, but that adds a null check to every cycle. Right now, I'm just allocating for much more space than should be necessary, but this is wasteful and could potentially break.
void func()
{
static int* outBuf[512]; //way too much
ReadBuffer(foo, (void**)outBuf);
}
Upvotes: 1
Views: 60
Reputation: 62583
First of all, many times a second is quite vague. Do you mean 100 times per second or 10 000 000 times per second? If the former (or close to it), I would not worry about null check at all and just do
void func() {
static int** outBuf = NULL;
if (outBuf == NULL)
outBuf = malloc(buf_sz * sizeof(int*));
// ...
}
The branch predictor will figure it out quite soon and if this is a hot code, will keep predicting.
Upvotes: 2