Segmentation fault in renderCopy()

After adding a map loader and a tile system to my game, this error has appeared. After some tests, I know that this comes from the function used to draw every tile. What is my error on that?

The function:

void Map::showInScreen(SDL_Renderer* renderer) {
    for (int i = 0; i < Map::_numberOfValidTiles; i ++) {
        SDL_Rect rect = Map::_tiles[i].rect;
        SDL_RenderCopy(renderer, Map::_tiles[i].sprite, NULL, &rect);
     }     
}        

The Tile struct:

struct Tile {                                                                                                                                        
    int sizeW, _sizeH;
    int posX, _posY;
    int collide;
    int visible;
    
    SDL_Rect rect;
    SDL_Texture* sprite;  
};  

Is the array Map::_tiles[i] large enough?

Mathias is correct, that array is probably being accessed from an invalid index in the heap.

If the program is crashing even when the map is empty of data, then go to the constructor for Map and initialize _numberOfValidTiles to Zero. Some operating systems will auto-initialize memory to zero before handing it to you, but some do not which means the variables are filled with junk data from the last program that used that spot in RAM. It’s best practice to initialize all variables.
That includes pointers like _tiles[i].sprite, if not initialized with an image, then set it to NULL.

If that does not fix the issue, then I would suspect an off-by-one error with the _numberOfValidTiles variable.

When I define the Map::_tiles I use this variable to size; Map::_tiles = new Tile[Map::_numberOfValidTiles];

I tried to use the sizeof(Map::_tiles) / sizeof(Map::_tiles[0]) instead of Map::_numberOfValidTiles, this stopped the seg fault, but, not is showing the tiles; this can be an off-by-one? I have never seen this error before, I really don’t know how to fix it; obs: I have been initialized all variables now, include the _tiles

Do you do this after _numberOfValidTiles has been initialized?

If _numberOfValidTiles is modified you will have to allocate a new larger array and use that instead. To make this easier, consider using std::vector instead of a dynamically allocated array.

This only works if Map::_tiles is actually an array. It looks like it’s a pointer and in that case it won’t work because sizeof(Map::_tiles) will give you the size of a pointer, not the size of the array.