1

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);
}
6
  • How about a suitably large circular buffer? Commented Aug 4, 2021 at 14:15
  • Huh? Why would it add a null check to every cycle? If malloc returned a null pointer, you are done. Print an error message and exit. From that point on, no null checks. Commented Aug 4, 2021 at 14:20
  • Do you want an array of integers, or an array of pointers to integers? The syntax in the question indicates the latter, though this may be unintentional based on the wording ("array", "buffer"). Commented Aug 4, 2021 at 14:32
  • you can't have your cake and eat it too. Either you need to preallocate as much as you could possibly use (meaning more than you might need on any given iteration), or allocate only as much as you need each time. It's a tradeoff between speed and memory usage. Unless this is a small embedded system with very constrained memory space, don't worry about it. 512 pointers is most likely 2048 or 4096 bytes. That's nothing. What do you mean by it "could potentially break"? Commented Aug 4, 2021 at 14:35
  • By potentially break, I mean that the ReadBuffer func might overwrite the size of the buffer. Commented Aug 4, 2021 at 17:40

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.