0

this code works fine before I add the string to the struct, then I get "Exception thrown: read access violation. _Pnext was 0xCDCDCDD1" in xmemory. I have marked the line with the error with a comment.

#include <iostream>
#include <string>

struct Test {
    Test() {}
    std::string name;
};

int main()
{
    Test* a;
    a = (Test*)malloc(2 * sizeof(Test));
    a[0] = Test(); // ERROR HERE
    std::cout << "Hello World!\n";
}
  • 1
    `malloc` just creates raw memory and does not construct the object in that memory. So the data members of `Test` are uninitialized. Therefore `a` does not point to a properly constructed `Test` object. Unless you are testing memory allocations avoid `malloc` and in most cases `new`. – Richard Critten Oct 06 '21 at 07:11
  • 0xCDCDCDD1 should be a tip-off: this is similar to the [filler value for uninitialized memory in Visual Studio](https://stackoverflow.com/a/127404/1548468) – Botje Oct 06 '21 at 07:15
  • The `Test` class is not trivially-copyable, thus `malloc`, `memset`, `memcpy`, and similar `C`-functions will not work correctly. C++ is not C. In C++, you must actually create the object, and `malloc` doesn't do that. – PaulMcKenzie Oct 06 '21 at 07:29

0 Answers0