memset() crash

closed account (10oTURfi)
I got 2D array(50x50) of structs:

PathfinderNode** PathfindingGrid;

1
2
3
4
5
6
7
8
9
10
11
12
struct PathfinderNode
{
    PathfinderNode* pParent;
    sf::Vector2i Position;
    int G, H;
    int Status;

    bool operator < (const PathfinderNode& first) const
    {
        return((this->G + this->H) < (first.G + first.H));
    }
};


Which was new'd like this:
1
2
3
4
5
6
PathfindingGrid  = new PathfinderNode*[50];

for(int i = 0; i < 50; ++i)
{
    PathfindingGrid[i] = new PathfinderNode[50];
}


I wanted a fast way to set all fields in each element of that 2D array to 0

So I did this:
std::memset(PathfindingGrid, 0, 50 * 50 * sizeof(PathfindingGrid[0][0]));
But it crashes :/

Please help
Last edited on
The PathfinderNode objects are not stored contiguous in memory so you can use a single memset call for all of them.

In C++ constructors are often used to initialize objects so you could define a default PathfinderNode constructor that initialize all members to 0.
closed account (10oTURfi)
I cant use constructor because I need to zero out PathfindingGrid every time I am generating a new path...

NVM, at least I know reason for crash, I solved this in a diferent way. Thanks.
Last edited on
Well, you could have a zeroOut member function that you call on all the nodes.

If you have to use memset, you can call memset in a loop.
1
2
3
4
for (int i = 0; i < 50; ++i)
{
	std::memset(PathfindingGrid[i], 0, 50 * sizeof(PathfinderNode));
}
But I guess you don't want that ...

Can the grid dimensions change? If not, why not define PathfindingGrid as
PathfinderNode PathfindingGrid[50][50];
That will make all nodes to be stored contiguous in memory so that you can use a single call to memset.

Another way is to define PathfindingGrid as
PathfinderNode* PathfindingGrid;
and allocate all the nodes in one call to new.
PathfindingGrid = new PathfinderNode[H * W];
To access an element at position (x, y) you do
PathfindingGrid[W * y + x]
I used W and H here as values for the width and height of grid.
closed account (10oTURfi)
- I thought of that, but there is a performance overhead

- Grid dimensions are different for each grid, so its no good

- Good idea! Thanks.
Topic archived. No new replies allowed.