我在这样的代码中有总线错误:
char* mem_original;
int int_var = 987411;
mem_original = new char [250];
memcpy(&mem_original[250-sizeof(int)], &int_var, sizeof(int));
...
const unsigned char* mem_u_const = (unsigned char*)mem_original;
...
const unsigned char *location = mem_u_const + 250 - sizeof(int);
std::cout << "sizeof(int) = " << sizeof(int) << std::endl;//it's printed out as 4
std::cout << "byte 0 = " << int(*location) << std::endl;
std::cout << "byte 1 = " << int(*(location+1)) << std::endl;
std::cout << "byte 2 = " << int(*(location+2)) << std::endl;
std::cout << "byte 3 = " << int(*(location+3)) << std::endl;
int original_var = *((const int*)location);
std::cout << "original_var = " << original_var << std::endl;
几次效果很好,打印出来:
sizeof(int) = 4
byte 0 = 0
byte 1 = 15
byte 2 = 17
byte 3 = 19
original_var = 987411
然后它失败了:
sizeof(int) = 4
byte 0 = 0
byte 1 = 15
byte 2 = 17
byte 3 = 19
Bus Error
它是在 Solaris OS (C++ 5.12) 上构建和运行的,Linux (gcc 4.12) 和 Windows (msvc-9.0) 上的相同代码运行良好。
我们可以看到:
- 内存是由 new[] 在堆上分配的。
- 内存是可访问的(我们可以逐字节读取)
- 内存完全包含应有的内容,而不是损坏的内容。
那么总线错误的原因可能是什么?我应该去哪里看?
UPD:
如果我最后 memcpy(...) location
,original_var
它可以工作。但是问题出在*((const int*)location)
哪里?