0

My window crashes when I try to use my function I created, I use it to create a sprite on screen but for some reason it crashes.

I get the error:

Segmentation fault (core dumped)

and here's my code:

#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
#include <string>
#include <unistd.h>
#include <iostream>
#include <vector>

using namespace std;

vector<sf::Sprite*> Tiles;

void createTile (string TextureIN, int x, int y) {

    sf::Vector2f Pos(x, y);

    sf::Texture Texture;
    Texture.loadFromFile(TextureIN);

    sf::Sprite *Tile;
    Tile->setTexture(Texture);
    Tile->setPosition(Pos);

    Tiles.push_back(Tile);
}

int main()
{
    sf::RenderWindow window(sf::VideoMode(800, 600), "My window");

    createTile("Recources/grass.png", 50, 50);

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

    window.clear(sf::Color::Blue);

    for (int i; i < Tiles.size(); i++) {
        window.draw(*Tiles[i]);
    }

    window.display();

    }

    return 0;
}

I had a working version before but my computer crashed and I forgot to back it up >.<

Anyways, I hope you can help me with this issue.

nvoigt
  • 75,013
  • 26
  • 93
  • 142

1 Answers1

2

You are creating a pointer without proper memory allocation.

So instead of

sf::Sprite *Tile; 

use

sf::Sprite *Tile = new sf::Sprite;

Be sure to have a look on How to avoid memory leaks when using a vector of pointers to dynamically allocated objects in C++? as well.

Community
  • 1
  • 1
Martin Sand
  • 482
  • 1
  • 8
  • 14