赋值运算符在 xcode 4 中崩溃,在MSVS2010中运行良好
Assignment operator crash in xcode 4, runs fine in MSVS2010
我正在使用Visual Studio 2010进行C++项目,一切都很好,但是当我尝试使用xcode 4运行我的程序时,它引发了Bas_Access异常。我认为这是因为内存泄漏,但我不确定如何解决问题。我有以下功能:
// Search is my class with x and y as members and here's is a constructor
// that I cretae in my Search.cpp class
Search& Search::operator=( const Search& search )
{
if(this != &search)
{
x = search.x;
y = search.y;
}
return *this;
}
以下是我的函数的调用方式:
Search searchStart(0,0);
//I created my tempSearch and initialized it with the start Search element
Search tempSearch(searchStart);
//bestSolution is a function that calculates the best neighbour node around the searchStart node, it returns a Search element. And stores it in a list in storage.
Search * tempCurrent=searchStart.bestSolution(&storage);
//Here I call my function
tempSearch=*tempCurrent;
我只是从现有元素创建一个新的搜索元素,但它给了我例外
x=search.x;
它与Visual Studio完美配合。
编辑:我刚刚添加了调用我的函数的代码。请原谅我无法提供完整的代码,因为它真的很长。
编辑:这是我最好的解决方案函数:
Search * searchNode::Search::bestSolution(Storage *storage )
{
//listResult is a type defined as std::list<Search *> listResult.
listResult::iterator it, it1;
listResult tempList;
//I've initialized the result element at (0,0) because it was creating problems
// if uninitialized
Search *result=new Search(0,0);
//openList is a simple list of Search elements
if(!storage->openList.empty()){
for(it=storage->openList.begin();it!=storage->openList.end();it++)
{
tempList.push_back((*it));
}
tempList.reverse();
it1=tempList.begin();
// getDistanceCost is a function that calculates the heuristic distance
// between two points and works fine
int fCost=(*it1)->getDistanceCost();
for(it1=storage->openList.begin();it1!=storage->openList.end();it1++)
{
if((*it1)->getDistanceCost()<=fCost){
fCost=(*it1)->getDistanceCost();
result=(*it1);
}
}
}
return result;
}
我的猜测是bestSolution
返回指向堆栈上分配的对象的指针。现在,当您尝试tempSearch=*tempCurrent
时,您正在尝试将值复制到此无效指针中,这会导致未定义的行为。
编辑
查看 bestSolution
方法的实现,我假设listResult
包含Search*
作为其节点,就像您正在执行result=(*it1);
一样。看起来列表具有指针的Search
对象在插入列表后被删除了。因此,列表中的内容是一个 invaid 指针。如果您尝试将任何内容复制到此无效指针所指向的内存中,则程序的行为将不可预测。
鉴于您提供的信息,可以肯定问题出在
Search * tempCurrent=searchStart.bestSolution(&storage);
它必须返回一些无效的指针(可能是NULL
(。
然后,这个无效的指针作为search
参数(更准确地说是&search
(传递给你的Search::operator=
,然后它试图访问这个无效指针(search.x
和search.y
(的x
(以及后来的y
(成员。
相关文章:
- 运行同一解决方案的另一个项目的项目
- CMake-按正确顺序将项目与C运行时对象文件链接
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- 代码在main()中运行,但在函数中出现错误
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何在运行中期切换GTK CSS style_context
- 如何在MS Visual Studio 2019中运行QT UI
- 如何通过cpp程序运行shell脚本
- IPC使用多个管道和分支进程来运行Python程序
- 删除指向指针的指针是运行时错误吗
- 如何用参数值调用函数(仅在运行时已知)
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- c++中的指针和运行时错误
- 在C应用程序中运行C++(带有STL)函数
- 运行程序时出现问题
- 控制允许动态运行c++的并发操作数
- 赋值运算符在 xcode 4 中崩溃,在MSVS2010中运行良好