• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
AlanSmithee

Segmentation fault on std::sort

11 posts in this topic

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)
[CODE]/* 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());
}
};
};[/CODE]


Pathfinding class header
[CODE]/* 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();
};[/CODE]

The pahtfinding class source
[CODE]#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;
}[/CODE]


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..

[CODE] if (Gridmanager::is_wall(ID))
{
return;
}[/CODE]

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.
0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites
This isn't a strict weak ordering:
[code]
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;
}
[/code]
Basically, a strict weak ordering acts like a less than. So [tt]return (a->get_f() < b->get_f())[/tt] would work. What you have always returns true.
0

Share this post


Link to post
Share on other sites
[code] 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;
}[/code]
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... :)
0

Share this post


Link to post
Share on other sites
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

[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());
}
};[/CODE]

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

Share this post


Link to post
Share on other sites
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 [url="http://gcc.gnu.org/bugzilla/show_bug.cgi?id=41448"]http://gcc.gnu.org/b...ug.cgi?id=41448[/url] :S

**Edit stable_sort gets rid of the seg fault
0

Share this post


Link to post
Share on other sites
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..
0

Share this post


Link to post
Share on other sites
[quote name='AlanSmithee' timestamp='1335129380' post='4933871']
And the debug call stack:

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

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 [color=#ff0000]bool cell_cmp::operator()(const std::shared_ptr<SearchCell>& a, const std::shared_ptr<SearchCell>& b) const[/color] is an empty shared_ptr.
0

Share this post


Link to post
Share on other sites
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:
[quote]
[left][background=rgb(250, 251, 252)]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?)[/background][/left]
[/quote]

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:


[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);
}
}[/CODE]

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

Share this post


Link to post
Share on other sites
Oops, sorry. Shame on me for not reading the whole thread before posting. [img]http://public.gamedev.net//public/style_emoticons/default/sleep.png[/img]
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0