【问题标题】:Segmentation fault in SFML when i try to draw an sf::Text object当我尝试绘制 sf::Text 对象时,SFML 中的分段错误
【发布时间】:2019-10-16 14:35:48
【问题描述】:

我正在将 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”,但正如我所说,程序崩溃了。

【问题讨论】:

  • 它在哪里崩溃?您看到的错误是什么?
  • 错误是双重释放或损坏(输出),我不确定它何时崩溃..我想当他试图删除文本或字体时,更具体地说,我收到信号 SIGABRT文件:new_allocator.h 位于 c++ 目录中
  • 如果你尝试不同的字体会怎样?
  • 我尝试使用开放的sans字体,错误一直到那里
  • 在每一行后面加上 printf 来检查它在哪里崩溃然后告诉我们。

标签: c++ segmentation-fault sfml


【解决方案1】:

好的,正如伯纳德所建议的那样,问题出在代码本身之外,我的 SFML 版本太旧了,我想是 2.3,我没有注意到它,因为我尝试使用命令 sudo 更新它upgrade/sudo update 它说一切都是最新的,所以当我注意到 SFML/Config.hpp 文件中的版本较旧时,我手动重新安装了 SFML,并从 SFML 网站获取了最新文件。感谢大家的时间和有用的提示:)

【讨论】:

    【解决方案2】:

    事件循环

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

    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

    【讨论】:

    • 是的,我知道,我删除了绘图功能不需要的代码部分,我检查了循环事件不会影响 sf::Text
    猜你喜欢
    • 2015-10-16
    • 2018-07-03
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多