1
struct st{
    string name;
};

int main() {
    st s1[10];
    {
        st s2[10];
        for (int i = 0; i < 10; i++) {
            s2[i].name = "name";
        }
        memcpy(&s1, &s2, sizeof(s2));

    }
    for (int i = 0; i < 10; i++) {
        cout << s1[i].name << endl;
    }
    return 0;
}

The above code successfully prints out the "name" ten times, but the seg-faults instead of terminating. I'm suspecting it has to do with the destructor for s2, but not sure. How should I deal with this?

ercprk
  • 13
  • 1
  • 4
  • 2
    You deal with it by not using a C library function, `memcpy`, which knows absolutely nothing, whatsoever, about C++ classes. Use `std::copy` instead of `memcpy`, here. See the linked question for more information. – Sam Varshavchik Nov 25 '19 at 00:36
  • idk, but maybe because you are copying memory allocated in the stack and so maybe will be badly deallocated the when default destructor deletes s1.. – Alberto Sinigaglia Nov 25 '19 at 00:43
  • 1
    @AlbertoSinigaglia It doesn't matter where the memory for the class instance is allocated. It is undefined behavior to `memcpy` non-trivial classes and `std::string` is non-trivial. It cannot be meaningfully copied through a `void*` pointer as `memcpy` does, because it uses dynamic memory allocation internally (hence non-trivial) requiring knowledge of the type of the copied object which `void*` lacks. – walnut Nov 25 '19 at 00:53
  • ommit memcpy here because it's not "trivially copyable". Put in your inner for loop s1[i] = s2[i]; – rifkin Nov 25 '19 at 01:07

0 Answers0