I have a function which is called many times in my project:
void foo(int bar)
{
char arr[1024];
//...do some operation on arr according to value of bar
}
Now, in some rare cases, I am getting a segmentation fault when the value of bar is large. I need to increase the size of arr, whose size I can know from value of bar.
The obvious solution seems to dynamically allocate memory for arr depending on size of bar. However, this function is called very frequently, and I think allocating memory each time can decrease performance.
What should be my strategy to tackle this?
Two suggestions:
foowill also get a buffer as a parameter from the calling function (if called from the same function in a loop, for example. I wouldn’t pass the buffer all over the program iffoois called from 100 different places). This way, you only have to allocate once the buffer needs to be increased.Edit:
Regarding #2, @David Heffernan got heat for suggesting the same option, as it might be a complication of the code. I don’t think the following is very complicated:
I’ve used similar code in some frequently invoked callback where I couldn’t reuse the buffer, and eliminating the malloc on most cases has definitely improved performance. Whether that’s the best solution for the OP I really don’t know.