0

can I use the memory of a dynamic array of integers with placement new?

int* p = new int[10]{};
std::string* pstr = new(p)std::string("Hi there");
std::cout << *pstr << std::endl;
pstr->~std::string();
delete[] p;

The code works fine but is it safe to do so? Thank you!

Rushikesh Talokar
  • 1,515
  • 4
  • 16
  • 32
Itachi Uchiwa
  • 3,044
  • 12
  • 26

1 Answers1

1

No, as written it's not safe, because you do not know for sure that sizeof (std::string) is <= 10 * sizeof (int).

If you add code to check for that then it's safe(r), something like:

size_t bytes_needed = sizeof (std::string);
size_t ints_needed = (bytes_needed + sizeof (int) - 1) / sizeof (int);
int *p = new int [ints_needed];
...

There might also be alignment issues however, so using aligned_alloc (and free) instead of new [] (and delete []) is a better bet.

Paul Sanders
  • 24,133
  • 4
  • 26
  • 48
  • This is not a problem: https://godbolt.org/z/f41qhqWvo (even though all compilers are implementing Small String Optimalization) explanation why this is wrong is much more complex. – Marek R Jun 07 '21 at 23:02
  • 1
    @MarekR I'm not saying it necessarily *is* a problem, I'm saying it *might be* a problem. `sizeof (std::string`) is platform-dependent. – Paul Sanders Jun 07 '21 at 23:03
  • yes by you just scratching the surface, what can went wrong with it. In 99% of cases it will just work. – Marek R Jun 07 '21 at 23:06
  • @MarekR So apart from alignment (which I have added to my answer), what else might go wrong? – Paul Sanders Jun 07 '21 at 23:07