0

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++?

0

1 Answer 1

1

You can indeed use std::vector, you don't need the C++11 initializer lists to make it work, just insert them:

std::vector<float> bins;

...

static const float tmpBins[] = {0.,20.,30.,40.,800.};
nBins = sizeof(tmpBins) / sizeof(tmpBins[0]);
bins.insert(bins.end(), tmpBins, tmpBins + nBins);

Or if you want to replace the current entries:

bins = std::vector<float>(tmpBins, tmpBins + nBins);
Sign up to request clarification or add additional context in comments.

1 Comment

Note that you may use assign instead of insert (and removing extra argument bins.end()).

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.