单行函数调用内存损坏了吗?

时间:2015-06-28 01:29:40

标签: c++ arrays pointers gdb

我从某些访问包含字符串的数组的代码中获得了seg错误。奇怪的是我在单行函数调用中丢失了内存。

所以这是我的代码:

class A {

    void method1(){

        std::cout << _myArray[ID] << std::endl;               //This outputs fine
        _pointerToObjectB->method2(ID, side);
    }

    std::array<std::string, 30000> _myArray;
    B* _pointerToObjectB;
};

在另一个班级:

class B {

    void method2(const int16_t ID, const int8_t Side) {
        std::cout << _objectA._myArray[ID] << std::endl;          //Seg fault
    }

    A _objectA;
};

GDB报告了一个seg错误,回溯:

#0  0x00007ffff05cd81c in std::string::_M_data() const () from /debug/bin/../lib/libstdc++.so.6
#1  0x00007ffff05cd85a in std::string::_M_rep() const () from /debug/bin/../lib/libstdc++.so.6
#2  0x00007ffff05cdeb8 in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::string const&) ()
   from /debug/bin/../lib/libstdc++.so.6
#3  0x00007fffe32f8bb1 in B<(short)-2, (short)1, (short)30000>::method2 (this=0x0, ID=362, Side=0 '\000')
#4  0x00007fffe32eafdf in A<(short)-2, (short)1, (short)30000>::method1 (this=0x2754400, ID=362, Side=0 '\000')

指针必须正常,因为它能够调用method2()。还有什么可能是错的?!

好像_objectA在整个通话中被删除了?

这个seg错误是一致的,每次运行程序时都会发生。我有点不知道接下来要做什么。

1 个答案:

答案 0 :(得分:3)

_pointerToObjectB未初始化。调试器输出中的this=0x0是一个死的赠品。 - Igor Tandetnik

对Igor答案的一个小修正:_pointerToObjectB并未指向B的实例。它是NULL。可能NULL偶然(真的未初始化),或者它可能已被初始化为NULL - 我们不知道因为你没有显示初始化代码。

  

如果指针为null,我没想到会发生方法调用吗?

这似乎是你误解的根源。

非虚拟方法调用完全不同于常规函数调用。编译器将其转换为:

Foo *foo = ...;
foo->Bar();

进入这个:

_ZN3Foo3Barv(foo);

其中_ZN3Foo3Barv只是编译器附加到Foo::Bar(void)方法定义的标签。实际上,你可以用普通的C来编写上面的调用,它会起作用。

虚方法的工作方式不同,通过NULL指针调用虚方法可能会按预期运行 - 在登陆被调用的方法之前崩溃