I have been reading C++ Primer Plus, and I'm stuck on this programming question:
This is what I have:Begin with the following structure declaration:
struct chaff
{
char dross[20];
int slag;
};
Write a program that uses placement new to place an array of two such structures in a
buffer. Then assign values to the structure members (remembering to use strcpy() for
the char array) and use a loop to display the contents. Option 1 is to use a static array,
like that in Listing 9.9, for the buffer. Option 2 is to use regular new to allocate the
buffer.
It compiles, but when I run it I get thisCode:#include <iostream> #include <new> using namespace std; struct chaff { char dross[20]; int slag; }; int main() { char * buf = new char(sizeof(chaff) * 2); chaff * c1 = new (buf) chaff; chaff * c2 = new (buf + sizeof(chaff)) chaff; strcpy(c1->dross, "Chaff 1"); c1->slag = 5; strcpy(c2->dross, "Chaff 2"); c2->slag = 2; chaff * c; for (int i = 0; i < 2; i++) { c = (chaff *) &buf[sizeof(chaff) * i]; cout << c->dross << endl; cout << c->slag << endl; } delete [] buf; }
First-chance exception at 0x7c91916a in book samples.exe: 0xC0000005: Access violation reading location 0x0037a8ed.
First-chance exception at 0x7c812afb in book samples.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x0012fc44..
Unhandled exception at 0x7c812afb in book samples.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x0012fc44..
The program '[3552] book samples.exe: Native' has exited with code 0 (0x0).