The code below works for me. How could this work? Wouldn’t this segfault?
char * buffer = new char[100];
float * in_buf = new(buffer) float[100];
Also i got a class like this:
class Item
{
public:
Item(int num)
{
u = new float[num];
v = new float[num];
}
float * u;
float * v;
//And many other variables
}
I want to create a block of memory and allocate v and u within them. Is this approach safe?
class Item
{
public:
Item(int num)
{
buffer = new char[(sizeof(char)+2*sizeof(float))*num];
u = new (buffer) float[num];
v = new (buffer+sizeof(float)*num) float[num];
}
char * buffer;
float * u;
float * v;
//And many other variables
}
What does “works” mean? As the
news here aren’t required to initialise/construct the data types in question, they don’t (necessarily) trigger reads or writes from the memory you’re implicity planning to use for them. So, one reason you may not see a segfault is that the code’s effectively only doing this:If you move on to read or write ala
in_buf[99] = 2;, you’re more likely to get a segfault but far from guaranteed – it could be that the memory at that address is in the applicaton’s virtual address space. For example, say the request for 100 characters was satisfied by a request for one page of memory and the OS page size was >= 4096 bytes – 1000 4-byte floats would coincidentally fit, or because an earliernewanddeletehad already mapped the memory. Even if it didn’t actually segfault immediately, it’s likely to crash or corrupt the heap or other heap-hosted data one day. More generally, there are plenty of unsafe things you can do in C++ that won’t actually bite immediately….Yes (assuming sane values of num), but it’s pointlessly complicated (and the extra character’s pointless and actively confusing). You could simply do: