gpt4 book ai didi

c++ - 这是一个 g++ 错误,libc 错误,还是我疯了(或者可能是三个)?

转载 作者:搜寻专家 更新时间:2023-10-31 00:42:34 26 4
gpt4 key购买 nike

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

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

测试应用.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 类完全按照原样指定时才会发生。如果您注释掉单个 vector (甚至是 bool 值),问题就会消失。如果您注释掉 _GLIBCXX_DEBUG,问题也会消失,但该标志应该是良性的 AFAIK。有什么建议吗?我应该在哪里提交错误?还是我忽略了一些明显的事情?

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

最佳答案

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

关于c++ - 这是一个 g++ 错误,libc 错误,还是我疯了(或者可能是三个)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11871582/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com