我一直在編寫一個測試用例程序來演示我的一個較大程序的問題, 和測試用例有一個原始程序沒有的錯誤。「地址不是來自malloc()」使用電子圍欄的錯誤
這裏的頭文件:
// compiled with g++ -I/usr/local/bin/boost_1_43_0 -Wall -std=c++0x -g test.cpp
#include <bitset>
#include <boost/shared_ptr.hpp>
#include <vector>
typedef std::vector< std::vector< std::bitset<11> > > FlagsVector;
namespace yarl
{
namespace path
{
class Pathfinder;
}
namespace level
{
class LevelMap
{
// Member Variables
private:
int width, height;
FlagsVector flags;
public:
boost::shared_ptr<path::Pathfinder> pathfinder;
// Member Functions
LevelMap(const int, const int);
int getWidth() const {return width;}
int getHeight() const {return height;}
bool getFifthBit(const int x, const int y) const
{
return flags.at(x).at(y).test(5);
}
};
class Level
{
// Member Variables
public:
LevelMap map;
// Member Functions
public:
Level(const int w=50, const int h=50);
};
}
namespace path
{
class Pathfinder
{
// Member Variables
private:
boost::shared_ptr<level::LevelMap> clientMap;
// Member Functions
public:
Pathfinder() {}
Pathfinder(level::LevelMap* cm)
: clientMap(cm) {}
void test() const;
};
}
}
,這裏是實現文件:
#include <iostream>
#include "test.hpp"
using namespace std;
namespace yarl
{
namespace level
{
LevelMap::LevelMap(const int w, const int h)
: width(w), height(h), flags(w, vector< bitset<11> >(h, bitset<11>())),
pathfinder(new path::Pathfinder(this))
{}
Level::Level(const int w, const int h)
: map(w,h)
{
map.pathfinder->test();
}
}
namespace path
{
void Pathfinder::test() const
{
int width = clientMap->getWidth();
int height = clientMap->getHeight();
cerr << endl;
cerr << "clientMap->width: " << width << endl;
cerr << "clientMap->height: " << height << endl;
cerr << endl;
for(int x=0; x<width; ++x)
{
for(int y=0; y<height; ++y)
{
cerr << clientMap->getFifthBit(x,y);
}
cerr << "***" << endl; // marker for the end of a line in the output
}
}
}
}
int main()
{
yarl::level::Level l;
l.map.pathfinder->test();
}
我這個節目與電動欄杆相連,當我運行它,它與此錯誤中止:
ElectricFence Aborting: free(bffff434): address not from malloc().
Program received signal SIGILL, Illegal instruction.
0x0012d422 in __kernel_vsyscall()
從gdb回溯顯示非法指令在編譯器中Pathfinder
的破壞函數,它在破壞其shared_ptr時遇到了問題。任何人都明白這是爲什麼?
將LevelMap的探路者從shared_ptr更改爲原始指針解決了問題,感謝您的幫助。作爲第二個問題,我在我的原始程序中使用了很多shared_ptrs,實際上這個例子中的原始指針是我唯一使用的非shared_ptr。你會建議將所有其他shared_ptr更改爲引用或原始指針嗎? – Max 2010-07-25 19:31:35
@Max:您應該使用'shared_ptr'和'weak_ptr'來管理_dynamically allocated_對象。只是不要使用它們來管理自動分配的對象。 – 2010-07-25 19:36:24