Code below causes segmentation fault on g++ 5.4.0 20160609. But it works on vs c++ 11.0.
#include <string>
#include <iostream>
#include <vector>
struct fooStruct{
std::string str;
fooStruct() : str(std::string("")){}
};
int main()
{
fooStruct fooObj;
std::vector<char> cont(sizeof(fooStruct));
std::cout<<"Size of string = "<<sizeof(std::string)<<std::endl;
std::cout<<"Size of vec = "<<cont.size()<<std::endl;
std::cout<<sizeof(fooObj)<<std::endl;
char* ptr = cont.data();
((fooStruct*)(ptr))[0] = fooObj; //segmentation fault
//((fooStruct*)(ptr))[0].str = fooObj.str; //segmentation fault
std::cout<<((fooStruct*)(ptr))[0].str<<std::endl;
return 0;
}
The only difference between compilers is that msvc takes 40 bytes for string, while gcc only 32. But i don't think that it does matter here. Why does it work on msvc and does not work on g++?