【发布时间】:2018-03-22 15:28:41
【问题描述】:
以下代码会导致 g++ 5.4.0 20160609 出现分段错误。但它适用于 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;
}
编译器之间的唯一区别是 msvc 需要 40 个字节作为字符串,而 gcc 只需要 32 个字节。但我认为这并不重要。 为什么在msvc上可以,在g++上不行?
【问题讨论】:
-
你的问题是什么?
-
我猜这就是他出现分段错误的原因。
-
((fooStruct*)(ptr))[0] = fooObj;不是直接违反了严格的别名和调用 UB 吗? -
“它可以工作”并不意味着它不是未定义的,分配给不存在的东西是未定义的。
标签: c++ visual-studio gcc