当我尝试绘制sf :: Text对象时,SFML中出现分段错误

时间:2019-10-16 14:35:48

标签: c++ segmentation-fault sfml

我正在将SFML用于学校项目,当我尝试运行此代码时遇到了这个问题,我得到了一个错误:两次释放或损坏(退出),程序崩溃。我的操作系统是ubuntu。

我尝试使用malloc创建“文本”。在那种情况下,没有任何错误,但是仍然会崩溃(我仍然遇到分段错误)。我什至尝试将这段代码发送给朋友,它对他有用,所以我认为我的配置有问题吗?

int main(){
    sf::RenderWindow window(sf::VideoMode(500, 320), " Text ");
    sf::Event event;
    sf::Font font;
    font.loadFromFile("../arial_narrow_7.ttf");
    sf::Text text("hello", font);
    text.setCharacterSize(30);
    text.setStyle(sf::Text::Bold);
    text.setFillColor(sf::Color::Red);
    text.setFont(font);

    while(window.isOpen()) {
        window.draw(text);
        window.display();
        window.clear();
    }
}

它应该以红色绘制文本“ hello”,但是正如我所说的,程序崩溃了。

2 个答案:

答案 0 :(得分:2)

好的,正如Bernard所建议的那样,问题出在代码本身之外,我的SFML版本太旧了,我认为2.3,我没有注意到它,因为我尝试使用命令 sudo更新它升级/ sudo更新,它表示一切都是最新的,因此当我注意到SFML / Config.hpp文件中的版本较旧时,我手动重新安装了SFML,而没有使用SFML网站上的最新文件。感谢大家的宝贵时间和有用的提示:)

答案 1 :(得分:0)

事件循环

您应该添加事件处理循环,以使窗口正常运行。

根据SFML tutorials

  

人们经常犯的一个错误是忘记事件循环,只是   因为他们尚不关心事件处理(他们使用实时   输入)。没有事件循环,窗口将变为   没有反应。重要的是要注意,事件循环有两个   角色:除了向用户提供事件外,它还为   窗口也有机会处理其内部事件,这是必需的   这样它就可以响应移动或调整用户操作的大小。

因此您的代码应如下所示:

#include <SFML/Window.hpp>

int main()
{
    sf::RenderWindow window(sf::VideoMode(500, 320), " Text ");
    sf::Font font;
    font.loadFromFile("../arial_narrow_7.ttf");
    sf::Text text("hello", font);
    text.setCharacterSize(30);
    text.setStyle(sf::Text::Bold);
    text.setFillColor(sf::Color::Red);
    text.setFont(font);
    // run the program as long as the window is open
    while (window.isOpen())
    {
        // check all the window's events that were triggered since the last iteration of the loop
        sf::Event event;
        while (window.pollEvent(event))
        {
            // "close requested" event: we close the window
            if (event.type == sf::Event::Closed)
                window.close();
        }
        window.clear();
        window.draw(text);
        window.display();
    }

    return 0;
}

您甚至在代码的开头声明了一个未使用的sf::Event