有一个微妙的错误在我们的软件中不会以可预测的方式显现出来。
当全局析构函数执行时会发生这种情况。通常这是一个“双重释放”错误,但我也看到过其他事情:NULL-ptr 取消引用、对未分配任何内容的地址的 ptr 取消引用、访问未对齐(因为指针有垃圾值)、与损坏的堆栈......这样的例子不胜枚举。
这些神秘且难以重现的错误的原因:微妙地违反了“单一定义规则”。
一点背景...
因为我还很小,所以这个软件是使用以下链接链接的-zmuldefs
链接器标志,指示链接器忽略如下情况。然后它被迫选择它遇到的第一个定义(当然链接器警告也被忽略):
$ cat /tmp/file1.cc
int x;
int main( int argc, char *argv[] ) { return x; }
$ cat /tmp/file2.cc
double x = 3.14159265358979;
$ gcc /tmp/file{2,1}.cc -o /tmp/test
/tmp/ccuTgbRy.o:(.bss+0x0): multiple definition of 'x'
/tmp/cchvHEav.o:(.data+0x0): first defined here
/usr/bin/ld: Warning: size of symbol 'x' changed from 8 in /tmp/ccYCIypE.o to 4 in /tmp/ccuTgbRy.o
collect2: error: ld returned 1 exit status
$ gcc /tmp/file{2,1}.cc -Wl,-zmuldefs -o /tmp/test
/usr/bin/ld: Warning: size of symbol 'x' changed from 8 in /tmp/ccWaeBBi.o to 4 in /tmp/ccSc9IiE.o
$ /tmp/test; echo $?
68
这与问题有什么关系
我遇到过四种基本情况会出现此问题:
$ cat /tmp/file1.cc
double x; // (1) If file2.cc is linked first it may end up on
// a dword boundary causing misaligned accesses
// when used as a double.
std::string mystring; // (2) If file2.cc is linked first, the actual size
// of the object is sizeof(char*) so
// std::string::string() will clobber memory
// after the pointer.
std::string another; // (3)
// file1.cc is compiled with -fPIC & put into a
// shared library
// file2.cc is NOT compiled with -fPIC & is put
// into an executable
//
// This will cause a very subtle problem: the two
// strings share the same piece of memory, but
// the constructor will execute once during the executable's
// _init() and once for each shared library with its own
// variable "another" when their _init() executes.
// The destructor will also execute multiple times
$ cat /tmp/file2.cc
int x;
char *mystring; // (4) Modifying through this ptr will cause undefined
// behavior when the other file's "mystring" is used
std::string another;
导致大小或对齐方式更改的变量应报告为链接器警告,因此有人可能倾向于通过重命名有问题的变量(或其他变量)来解决问题。
但是,在以下情况下无法看出问题是否存在:
- 对象大小相同(x 定义为 float/int & sizeof(float) == sizeof(int))
- 违规变量(具有相同的大小和类型)存在于多个库和/或可执行文件中
确保您消除所有这些问题的唯一解决方案:
- 摆脱
-zmuldefs
- 确保所有声明都来自标头/包含定义它的标头
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)