这是一个 g++ 错误、libc 错误还是我疯了(或者三者兼而有之)



当我遇到内存访问错误时,我正在使用一些openFrameworks示例。经过一天的缩小问题范围,我有一个相当小的相对纯净的C++代码样本,它仍然会导致内存访问错误。我将在这里发布整个内容,因为它很短。

有三个文件:testApp.cpp、main.cpp和testApp.h。

testApp.h:

#include <cstdlib>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class X {
public:
  X();
  virtual ~X();
private:
  vector<string> vertices;
  vector<string> colors;
  vector<string> normals;
  vector<string> texCoords;
  vector<string> indices;
  bool bVertsChanged, bColorsChanged, bNormalsChanged, bTexCoordsChanged, bIndicesChanged;
  int mode;
  string name;
  bool useColors;
  bool useTextures;
  bool useNormals;
};
class testApp{
public:
  void setup();
  X x1;
  X x2;
  vector<string> stroke;
};

测试应用.cpp:

#include "testApp.h"
X::X() {}
X::~X() {}
void testApp::setup(){
  std::cout << stroke.size() << std::endl;

}

主.cpp:

#define _GLIBCXX_DEBUG
#include "testApp.h"
int main( ){
    testApp* o = new testApp();
    o->setup();
    std::cout << o->stroke.size() << std::endl;
}

为了编译,我输入了:g++ -o testApp testApp.cpp main.cpp .(我使用的是 Ubuntu 12.04 和库存 g++ 编译器版本 4.6.3,x86_64架构)。当我运行它时,我得到以下输出:

18446744073709025734
0

第一个数字来自调用testApp::setup,它打印出stroke.size()(这显然是不正确的)。第二个数字来自直接打印 stroke.size()。似乎存在某种内存问题,但我不知道从哪里开始,或者在哪里提交错误。

这似乎只有在 testApp 类被完全指定时才会发生。如果你注释掉一个向量(甚至一个布尔值),问题就会消失。如果你注释掉_GLIBCXX_DEBUG,问题也会消失,但那个标志应该是良性的AFAIK。有什么建议吗?我应该在哪里提交错误?还是我忽略了什么明显的东西?

另外,有人介意在自己的计算机/编译器上尝试一下,看看他们是否遇到同样的问题吗?

_GLIBCXX_DEBUG可能会更改标准库容器的定义,因此您的程序违反了一个定义规则 (ODR)。 X 的定义在主翻译单元和 testApp.cpp 翻译单元中.cpp不同,会产生未定义的行为。

最新更新