内存仅在gcc上发生意外更改
Memory altered unexpectedly only on gcc?
在下面的代码中,char* d
的内存地址在100ms后发生了更改,我没有做任何更改。有人能解释一下下面代码中哪里是未定义的行为吗?
此行为仅在gcc 4.8.2上可见,在visualstudio 2012上不可见。
#include <iostream>
#include <string>
#include <boost/thread.hpp>
#include <chrono>
using namespace std;
class state_p
{
public:
unsigned char* state;
void init(unsigned char* state_in)
{
state = state_in;
}
};
void state_link(unsigned char* &state)
{
for(unsigned int i = 0; i < 10; i++)
{
state_p s;
s.init(state+184*i);
}
}
void go_sleep(unsigned int ms)
{
boost::this_thread::sleep(boost::posix_time::milliseconds(ms));
}
class main_class
{
private:
char *d;
unsigned s;
char* a;
void core()
{
while(true)
{
cout << "A_CORE: " << (void*)d << "n";
}
}
public:
main_class() {}
main_class(char *di)
{
d = di;
boost::thread start_core_thread(&main_class::core, this);
}
};
void show(unsigned int &i)
{
cout << i;
go_sleep(100000000);
}
int main()
{
unsigned char *state = (unsigned char*)calloc(3072, sizeof(char));
char st = 100;
main_class main_c;
main_c = main_class(&st);
state_link(state);
go_sleep(100);
unsigned int i = 0;
show(i);
}
输出:
A_CORE: 0x186a0
A_CORE: 0x186a0
A_CORE: 0x186a0
A_CORE: 0x186a0
A_CORE: 0x186a0
A_CORE: 0x186a0
A_CORE: 0x186a0
A_CORE: 0x186a0
A_CORE: 0
A_CORE: 0
A_CORE: 0
A_CORE: 0
此处:
main_c = main_class(&st);
创建并销毁临时main_class
,然后将其复制到main_c
。此处:
boost::thread start_core_thread(&main_class::core, this);
将指向该临时对象的指针绑定到线程。线程在它被破坏后继续访问它,从而产生未定义的行为。特别是,如果临时对象的存储被重新用于另一个对象,您很可能会看到值的变化。
如果您要直接初始化非临时对象:
main_class main_c(&st);
那么您应该回到定义良好的行为领域。您可以考虑使类不可复制,以防止出现此错误。
您还应该显式分离线程,或者将其作为类成员保留以稍后加入。Boost中不赞成在不连接或分离线程对象的情况下销毁线程对象,而在标准库中则禁止销毁线程对象。
相关文章:
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 奇怪的结构&GCC&clang(void*返回类型)
- GCC本机矩阵运算库
- PowerPC ppc64le上的Gcc Woverloaded虚拟错误
- 在C++中对T*类型执行std::move的意外行为
- gcc和c++17的过载解析失败
- 数据成员SFINAE的C++17测试:gcc vs clang
- GCC对可能有效的代码抛出init list生存期警告
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 使用 GCC 卸载的 OpenMP 卸载失败,并出现"Ptx assembly aborted due to errors"
- 为什么与常规GCC不同,即使有"学究性错误",MinGW-GCC也能容忍丢失的返回类型
- 使用gcc从静态链接的文件中查找可选符号
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 普通环路未使用gcc 4.8.5自动矢量化
- 在gcc中意外调用了Const重载.编译器错误或兼容性修复程序
- 在 mingw 的 gcc-5.3 下具有混合位域和枚举递减的结构的意外大小
- 内存仅在gcc上发生意外更改
- GCC优化导致意外返回值
- std::exception. .()在clang和gcc上返回意外值,但在VS11上没有
- 在GCC和Clang下,带有lambda的简单RAII包装器的复制初始化意外失败