c++ - 使用 -O3 编译时出现奇怪的段错误

标签 c++ gcc gcc4.7

以下代码在 Debian 7 上的 g++ 4.7.2-5 上编译并正常工作。

#include <iostream>
#include <string.h>

using namespace std;

class mystring {
  char * buf;
  static char * dupbuf(const char * buf) {
    char * result = new char[strlen(buf) + 1];
    strcpy(result, buf);
    return result;
  }

  public:
    mystring(const char * o)
    : buf(dupbuf(o)) {}

    ~mystring() { delete[] buf; }
    mystring(const mystring &) = delete;
    mystring & operator=(const mystring&) = delete;

    void write(ostream & o) const {
      if (!buf) { exit(1); } // remove me
      o << buf;
    }
};

ostream & operator <<(ostream & o, const mystring & ms) {
  ms.write(o);
};

int main() {
    mystring m("hello");
    cout << m << endl;
    return 0;
}

...除非您使用 -O2 或更高版本进行编译。然后它会出现段错误,并且 valgrind 声称从 0x0 读取无效。我猜有一些堆栈损坏,但我这辈子都找不到它。

有趣的是,删除标记为“remove me”的行会使问题消失。将 endl 添加到 write 也是如此。有什么想法吗?

最佳答案

ostream & operator <<(ostream & o, const mystring & ms) {
  ms.write(o);
};

这会导致未定义的行为,因为它不返回任何内容。此外,命名空间级别的空声明(“;”)是完全没有必要的(并且在旧的 C++ 标准中曾经是非法的)。

关于c++ - 使用 -O3 编译时出现奇怪的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25117385/

相关文章:

linux - GCC 本地安装 Ubuntu

c++ - 如何释放函数内分配的任何动态内存?

c++ - Boost Spirit Classic - 微型 SQL 解析器

c++ - 有目的地多次链接同一个对象时,如何避免多个定义错误?

gcc - gcc -march选项的默认设置是什么?

无法在 gcc ubuntu linux 中正确输入字符串

python - 执行销毁令

c++ - C++控制台中的星号列出了文件夹中的所有文件,为什么?

c - 在 LINUX 中创建共享库会抛出错误

linux - memcpy memmove GLIBC_2.14/2.2.5的解释