Duplicating elements inside a StringArray


#1

Not sure if this is a bug. What I did was something like this:

StringArray words("First", "Second");
for(int i = 0; i < N; i ++)
  words.add(words[i % 2]);

Which will result in a segfault for some large enough N, and, I know why - StringArray::add takes a reference, but the reference was taken fresh from itself, whose address might move if there’s a realloc. Here’s a simple workaround,

StringArray words("First", "Second");
for(int i = 0; i < N; i ++) {
  String copy = words[i % 2];
  words.add(copy);
}

The fix looks somewhat redundant (but it’s definitely necessary!). I find this little pitfall annoying.


#2

Interesting edge case!

My first thought about this was that surely it’s something that would affect all containers, e.g. std::vector, but I guess that they don’t use realloc, so will allocate the new array and copy the source into it before freeing the old one. Maybe this is why they don’t use realloc!

Thanks for the heads-up, I’ll figure out a workaround for StringArray, which can be done using a move operation for very little overhead. It’ll also affect some other classes like Array, which won’t be as easy to “fix” because it could add unknown overhead depending on the type - but it’s pretty simple to add assertions to at least catch this situation and let the user find a workaround.