Jump to content

  • Log In with Google      Sign In   
  • Create Account


Segmentation fault on std::sort


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
11 replies to this topic

#1 AlanSmithee   Members   -  Reputation: 960

Like
0Likes
Like

Posted 22 April 2012 - 03:01 PM

Hello.

I am setting up A* pathfinding for my game in C++ and SDL.
I have only the basic knowledge of how A* and pathfinding works so I've been going by different tutorials and help from friends.

Here is the code involved:

SearchCell: (node)
/* Includes */
#include <math.h>
#include "Constants.h"
#include <fstream>
#include <limits>

/* Node for A* */
struct SearchCell
{
	int x, y, ID;

	SearchCell* parent;

	float G;	// Accumelated distance from start node to were the cell is
	float H;	// Hueristic, estimated distance to the goal

	SearchCell() : parent(0) {};
	SearchCell(int X, int Y, int id, SearchCell* Parent) :
		x(X),
		y(Y),
		parent(Parent),
		ID(id),
		G(0.0f),
		H(0.0f)
	{};

	float get_f()
	{
		return G + H;
	};

	float heuristic(SearchCell* nodeEnd)
	{
		float x = static_cast<float>(fabs(static_cast<float>(this->x - nodeEnd->x)));
		float y = static_cast<float>(fabs(static_cast<float>(this->y - nodeEnd->y)));

		return x + y;
	};
	
	// Comparison operators
	inline bool operator<(std::shared_ptr<SearchCell>& a) { return get_f() < a->get_f(); }
	inline bool operator<=(std::shared_ptr<SearchCell>& a) { return get_f() <= a->get_f(); }
	inline bool operator>(std::shared_ptr<SearchCell>& a) { return get_f() > a->get_f(); }
};

// for std::sort

struct cell_cmp
{
	bool operator()(const std::shared_ptr<SearchCell>& a, const std::shared_ptr<SearchCell>& b) const
	{
		return (a->get_f() < b->get_f());
	}
};
};


Pathfinding class header
/* Includes */
#include <vector>
#include <tr1/memory>
#include "Logic.h"
#include "SearchCell.h"
#include "Gridmanager.h"

class Pathfinder
{
	public:
		Pathfinder();
		~Pathfinder();

		Point3 next_path_pos();

		bool find_path(Point3, Point3);
		bool foundGoal;

	private:
		typedef std::shared_ptr<Point3> pointPtr;
		typedef std::shared_ptr<SearchCell> cellPtr;

		cellPtr startCell;
		cellPtr goalCell;
		
		std::vector<cellPtr> openList;
		std::vector<cellPtr> visitedList;
		std::vector<pointPtr> pathList;
		
		cellPtr get_next_cell();
		void add_cell(int, int, float, SearchCell*);
		void search_path();
};

The pahtfinding class source
#include "Pathfinder.h"
#include "Camera.h"
#include <fstream>
#include <algorithm>

Pathfinder::Pathfinder()
{
	startCell.reset();
	goalCell.reset();

	foundGoal = false;

	openList.reserve(MAP_WIDTH * MAP_HEIGHT);
}

Pathfinder::~Pathfinder()
{
}


bool Pathfinder::find_path(Point3 currentPos, Point3 targetPos)
{
	if (foundGoal)
	{
		openList.clear();
		visitedList.clear();
		pathList.clear();
	}

	// Start and goal in units rather then pixels (tiles are squares so same width as height)
	currentPos /= TILE_WIDTH;
	targetPos /= TILE_WIDTH;

	startCell.reset(new SearchCell(currentPos.x, currentPos.y, (currentPos.y*MAP_WIDTH)+currentPos.x, 0));
	goalCell.reset(new SearchCell(targetPos.x, targetPos.y, (targetPos.y*MAP_WIDTH)+targetPos.x, 0));

	startCell->H = startCell->heuristic(goalCell.get());
	openList.push_back(startCell);

	foundGoal = false;

	search_path();

	return foundGoal;
}


std::shared_ptr<SearchCell> Pathfinder::get_next_cell()
{
	// This causes segmentation fault
	std::sort(openList.begin(), openList.end(), cell_cmp());

	cellPtr nextCell = openList.front();
	visitedList.push_back(nextCell);
	openList.erase(openList.begin());

	return nextCell;
}


void Pathfinder::add_cell(int x, int y, float newCost, SearchCell* parent)
{
	int ID = y * MAP_WIDTH + x;
	int screenX = x * 16;
	int screenY = y * 16;

	if (!Gridmanager::is_within_screen(screenX, screenY))
	{
		return;
	}

	if (!Gridmanager::is_within_grid(x, y))
	{
		return;
	}

	// The segmentationfault only occours when i check for this
	if (Gridmanager::is_wall(ID))
	{
		return;
	}

	for (unsigned int i = 0; i < openList.size(); i++)
	{
		if (ID == openList[i]->ID)
		{
			if (openList[i]->G <= newCost)
			{
				return;
			}
			else
			{
				openList.erase(openList.begin() + i);
				break;
			}
		}
	}

	cellPtr newChild(new SearchCell(x, y, ID, parent));
	newChild->G = newCost;
	newChild->H = newChild->heuristic(goalCell.get());
	openList.push_back(newChild);

}

void Pathfinder::search_path()
{
	while (!openList.empty())
	{
		cellPtr currentCell = get_next_cell();

		if (currentCell->ID == goalCell->ID)
		{
			goalCell->parent = currentCell->parent;

			SearchCell* getPath = goalCell.get();

			while (getPath->parent != NULL)
			{
				pathList.push_back(pointPtr(new Point3));
				pathList.back()->x = getPath->x;
				pathList.back()->y = getPath->y;
				getPath = getPath->parent;
			}

			foundGoal = true;
			return;
		}
		else
		{

			// East cell
			add_cell(currentCell->x + 1, currentCell->y, currentCell->G + 1.0f, currentCell.get());

			// West cell
			add_cell(currentCell->x - 1, currentCell->y, currentCell->G + 1.0f, currentCell.get());

			// North cell
			add_cell(currentCell->x, currentCell->y + 1, currentCell->G + 1.0f, currentCell.get());

			// South cell
			add_cell(currentCell->x, currentCell->y - 1, currentCell->G + 1.0f, currentCell.get());

			// East-North cell
			add_cell(currentCell->x + 1, currentCell->y + 1, currentCell->G + 1.414f, currentCell.get());

			// West-North cell
			add_cell(currentCell->x - 1, currentCell->y + 1, currentCell->G + 1.414f, currentCell.get());

			// East-South cell
			add_cell(currentCell->x + 1, currentCell->y - 1, currentCell->G + 1.414f, currentCell.get());

			// West-South cell
			add_cell(currentCell->x - 1, currentCell->y - 1, currentCell->G + 1.414f, currentCell.get());
		}
	}

	foundGoal = false;
	openList.clear();
	visitedList.clear();
}


Point3 Pathfinder::next_path_pos()
{
	Point3 nextPos(0, 0, 0);
	nextPos.x = goalCell->x;
	nextPos.y = goalCell->y;

	if (!pathList.empty())
	{
		nextPos = *pathList.back();
		pathList.pop_back();
	}

	if (pathList.empty())
	{
		openList.clear();
		visitedList.clear();
		foundGoal = false;
	}

	nextPos *= TILE_WIDTH;

	return nextPos;
}


Everything is working well except for the fact that i get these wierd segmentation faults when i try to order my open list with std::sort
std::sort(openList.begin(), openList.end(), cell_cmp());

But this only happends when i check for walls though..

if (Gridmanager::is_wall(ID))
	{
		return;
	}

If i comment out the above section it works alot faster but ofcourse the walls are ignored but the vector gets sorted fine with no segmentation fault.

If I comment out the sort part, the actual pathfinding works but it takes sooo long for it to be calculated.

I have searched alot on the net and this is the things ive tried:

"strict weak order"
I understand that one cause for segmentation fault with std::sort can be ambigious sorting methods. Please see the first code section (SearchCell) I am pretty sure this works as inteded (and the sort DOES work when i dont check for walls?!)


NULL pointers.
I dont have the best understanding of std::shared_ptr but i did check so the ptrs arent NULL and they dont seem to be.
Now this does seems like the most likely reason becaus when the add_cell method returns under different circumstances, there are no problems.


Debug
When debugging the callstack backwards go like this (when the crash occours):

#0 00424842 SearchCell::get_f(this=0x0)
#1 00427549 cell_cmp::operator() (this=0x22f92c, a=@0x33300b8, b=@0x22f988)

So, as you can see the compare function gets called with valid memory adresses (i think?) but the get_f() (method used for comparison) gets caleld by 0x0 (NULL pointer?)

As you can see i dont really understand what is happening, but ive tried everything and i am at a loss.

Thanks in advance for your help! / AS.

Sponsor:

#2 ApochPiQ   Moderators   -  Reputation: 14345

Like
0Likes
Like

Posted 22 April 2012 - 03:10 PM

What's the actual text of the error you're seeing? It contains important information as to what exactly is going wrong.

#3 AlanSmithee   Members   -  Reputation: 960

Like
0Likes
Like

Posted 22 April 2012 - 03:16 PM

Hey!
Thanks for the quick post.

When i run the build normally it just gets a run-time error:
Process terminated with status 3 (0 minutes, 1 seconds)

When debugging i recive a pop-up message saying
"Program recieved signal SigSEGV, segmentation fault."

And the debug info:
Building to ensure sources are up-to-date
Build succeeded
Selecting target:
Debug
Adding source dir: C:\Projects\Individuellt Mjukvaruutvecklingsprojekt\Game\DungeonsOfZiro\
Adding source dir: C:\Projects\Individuellt Mjukvaruutvecklingsprojekt\Game\DungeonsOfZiro\
Adding file: bin\Debug\DungeonsOfZiro.exe
Starting debugger:
done
Registered new type: wxString
Registered new type: STL String
Registered new type: STL Vector
Setting breakpoints
Debugger name and version: GNU gdb 6.8
Child process PID: 5700
Program received signal SIGSEGV, Segmentation fault.
At C:/Projects/Individuellt Mjukvaruutvecklingsprojekt/Game/DungeonsOfZiro/files/SearchCell.h:33

And the debug call stack:

#0 00424842 SearchCell::get_f(this=0x0) (C:/Projects/Individuellt Mjukvaruutvecklingsprojekt/Game/DungeonsOfZiro/files/SearchCell.h:33)
#1 00427549 cell_cmp::operator() (this=0x22f92c, a=@0x33300b8, b=@0x22f988) (C:/Projects/Individuellt Mjukvaruutvecklingsprojekt/Game/DungeonsOfZiro/files/SearchCell.h:55)
#2 00000000 0x0047bd58 in std::__unguarded_partition<__gnu_cxx::__normal_iterator<std::shared_ptr<SearchCell>*, std::vector<std::shared_ptr<SearchCell>, std::allocator<std::shared_ptr<SearchCell> > > >, std::shared_ptr<SearchCell>, cell_cmp>(__first={_M_current = 0x33300b8}, __last={_M_current = 0x33300b8}, __pivot={<std::__shared_ptr<SearchCell, (__gnu_cxx::_Lock_policy) (c:/program files/codeblocks/mingw/bin/../lib/gcc/mingw32/4.4.1/include/c++/bits/stl_algo.h:2230)
#3 0047B114 std::__introsort_loop<__gnu_cxx::__normal_iterator<std::shared_ptr<SearchCell>*, std::vector<std::shared_ptr<SearchCell>, std::allocator<std::shared_ptr<SearchCell> > > >, int, cell_cmp>(__first={_M_current = 0x3330020}, __last={_M_current = 0x33300b8}, __depth_limit=7, __comp={<No data fields>}) (c:/program files/codeblocks/mingw/bin/../lib/gcc/mingw32/4.4.1/include/c++/bits/stl_algo.h:2301)
#4 0047C83E std::sort<__gnu_cxx::__normal_iterator<std::shared_ptr<SearchCell>*, std::vector<std::shared_ptr<SearchCell>, std::allocator<std::shared_ptr<SearchCell> > > >, cell_cmp>(__first={_M_current = 0x3330020}, __last={_M_current = 0x33300b8}, __comp={<No data fields>}) (c:/program files/codeblocks/mingw/bin/../lib/gcc/mingw32/4.4.1/include/c++/bits/stl_algo.h:5258)
#5 00407395 Pathfinder::get_next_cell(this=0x332f5cc) (C:\Projects\Individuellt Mjukvaruutvecklingsprojekt\Game\DungeonsOfZiro\files\Pathfinder.cpp:50)
#6 00407758 Pathfinder::search_path(this=0x332f5cc) (C:\Projects\Individuellt Mjukvaruutvecklingsprojekt\Game\DungeonsOfZiro\files\Pathfinder.cpp:109)
#7 00407317 Pathfinder::find_path(this=0x332f5cc, currentPos={x = 2, y = 6, z = 0}, targetPos={x = 25, y = 6, z = 0}) (C:\Projects\Individuellt Mjukvaruutvecklingsprojekt\Game\DungeonsOfZiro\files\Pathfinder.cpp:42)
#8 00424EE6 Dynamicobject::find_path(this=0x332f5b4, goalPos={x = 400, y = 100, z = 0}) (C:/Projects/Individuellt Mjukvaruutvecklingsprojekt/Game/DungeonsOfZiro/files/Dynamicobject.h:129)
#9 004059A4 Isles(this=0x3070020) (C:\Projects\Individuellt Mjukvaruutvecklingsprojekt\Game\DungeonsOfZiro\files\Isles.cpp:78)
#10 00404384 Game::run(this=0x22fdf0) (C:\Projects\Individuellt Mjukvaruutvecklingsprojekt\Game\DungeonsOfZiro\files\Game.cpp:116)
#11 0040455E SDL_main(argc=1, argv=0x3a13d8) (C:\Projects\Individuellt Mjukvaruutvecklingsprojekt\Game\DungeonsOfZiro\files\Game.cpp:164)
#12 004093DB console_main(argc=1, argv=0x3a13d8) (./src/main/win32/SDL_win32_main.c:315)
#13 00409498 WinMain(hInst=0x400000, hPrev=0x0, szCmdLine=0x65282f "", sw=10) (./src/main/win32/SDL_win32_main.c:398)
#14 00000000 0x00408d66 in main() (??:??)


I am using Code::blocks if it mathers.. there are no further messages, nor any compile-time errors.

#4 SiCrane   Moderators   -  Reputation: 9423

Like
0Likes
Like

Posted 22 April 2012 - 03:16 PM

This isn't a strict weak ordering:
        bool operator()(const std::shared_ptr<SearchCell>& a, const std::shared_ptr<SearchCell>& b) const
        {
                if (a->get_f() <= b->get_f())
                        return true;

                else if (a->get_f() > b->get_f())
                        return true;
        }
Basically, a strict weak ordering acts like a less than. So return (a->get_f() < b->get_f()) would work. What you have always returns true.

#5 Martins Mozeiko   Crossbones+   -  Reputation: 1413

Like
0Likes
Like

Posted 22 April 2012 - 03:20 PM

bool operator()(const std::shared_ptr<SearchCell>& a, const std::shared_ptr<SearchCell>& b) const
		{
				if (a->get_f() <= b->get_f())
						return true;

				else if (a->get_f() > b->get_f())
						return true;
		}
I don't get this.
if A <= B then you return true, but if A > B then you also return true. So why bother comparing something - just return always true.

Edit: too late... :)

#6 AlanSmithee   Members   -  Reputation: 960

Like
0Likes
Like

Posted 22 April 2012 - 03:20 PM

Thanks for pointing that out guys =)

For clarification: the opertor() function that i posted in the original post was just a wierd attempt of me to try to fix the error (combined with a typo.. (double return true))

the function that i am using and have been using all along with the same result is:
*edit: im gonna edit this in the original post to reflect my actual code

struct cell_cmp
{
	bool operator()(const std::shared_ptr<SearchCell>& a, const std::shared_ptr<SearchCell>& b) const
	{
		return (a->get_f() < b->get_f());
	}
};

So, i wish that was the problem but its not =(

#7 AlanSmithee   Members   -  Reputation: 960

Like
0Likes
Like

Posted 22 April 2012 - 04:43 PM

Hmm.. a small update..

It kind of looks like the segmentation fault only occours when both a.get_f() and b.get_f() are floating point numbers and equal to each other..
If they are equal but whole integers there is no problem.. and also when they are floating point numbers but not equal its ok too.. wierd..

Maybe I can fix it with this information..


*Edit.. and here seem to be my answer http://gcc.gnu.org/b...ug.cgi?id=41448 :S

**Edit stable_sort gets rid of the seg fault

#8 ApochPiQ   Moderators   -  Reputation: 14345

Like
0Likes
Like

Posted 22 April 2012 - 07:52 PM

Any particular reason you're using Code::Blocks instead of Visual C++ Express? The debugger is infinitely better :-)

#9 AlanSmithee   Members   -  Reputation: 960

Like
0Likes
Like

Posted 23 April 2012 - 08:52 AM

To be honest, no :P

I have a student licens on all microsoft software development tools via my unis MSDNAA licens and I have VS 2010 ultimate which I use for coding in C# and ASP.NET.

I just started using C::B long ago when i first started learning C++ and stuck to it.. I do agree however that VS debugger is awesome... I really should switch..

#10 Red Ant   Members   -  Reputation: 447

Like
0Likes
Like

Posted 24 April 2012 - 11:20 PM

And the debug call stack:

#0 00424842 SearchCell::get_f(this=0x0) (C:/Projects/Individuellt Mjukvaruutvecklingsprojekt/Game/DungeonsOfZiro/files/SearchCell.h:33)


Well, there's your problem. You're invoking the get_f() method on a null pointer.


EDIT: This means one of your operands in a call to bool cell_cmp::operator()(const std::shared_ptr<SearchCell>& a, const std::shared_ptr<SearchCell>& b) const is an empty shared_ptr.

#11 AlanSmithee   Members   -  Reputation: 960

Like
0Likes
Like

Posted 25 April 2012 - 12:31 PM

Hi Red Ant, thanks for your respons.

See, that was what I thought as well, as you can see from what I said in my original post:

So, as you can see the compare function gets called with valid memory adresses (i think?) but the get_f() (method used for comparison) gets caleld by 0x0 (NULL pointer?)


But then why does it work when I change nothing but the sort to stable_sort? Since the operands are still the same..

I got everything to work just fine though.. And now, after some optimization I am no longer using any sorting method at all, but rather putting objects in the vector in order already on insertion, with this bit of code:


void Logic::push_searchCell(std::vector<std::shared_ptr<SearchCell> > &v, std::shared_ptr<SearchCell> &a)
{
	if (v.size() == 0)
	{
		v.push_back(a);
		return;
	}

	v.insert(v.begin() + sort_searchCells(v, 0, v.size() - 1, a->get_f()), a);
}

//Find an element in vector v by a chosen value via binary search
const short int Logic::sort_searchCells(std::vector<std::shared_ptr<SearchCell> > &v, int start, int stop, int numb)
{
	if (start > stop)
	{
		return start;
	}

	int mid = (start + stop)/2;

	if (numb < v.at(mid)->get_f())
	{
		return sort_searchCells(v, start, mid-1, numb);
	}
	else
	{
		return sort_searchCells(v, mid+1, stop, numb);
	}
}

Saved me a few ms on each call to find path and solved any future ?-marks regarding the sorting =)

#12 Red Ant   Members   -  Reputation: 447

Like
0Likes
Like

Posted 25 April 2012 - 02:06 PM

Oops, sorry. Shame on me for not reading the whole thread before posting. Posted Image




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS