I just found this "gem" in some code that was randomly crashing. It is supposed to assign an array of floats to bins and the number of bins to nBins. Depending on some conditions there are different arrays with different sizes. Of course this fails (or is undefined behavior) because tmpBins goes out of scope, and the compiler can reuse its memory.
float* bins = 0;
int nBins = 5;
if (condition1) {
float tmpBins[] = {0.,20.,30.,40.,800.};
bins = tmpBins;
nBins = 5;
} else {
// more cases
}
I wonder how I should fix this. I could allocate memory with new and copy it over with memcpy or a loop. I could use a vector, but I don't have C++11's vector initializers, so I'd probably have to add the elements manually with push_back, which I'd like to avoid. I'd rather not change too much of the surrounding legacy code, so if I change the type of bins it should still be usable as an drop-in replacement for an array. What's the best/most ideomatic way of fixing this in C++?