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

Segmentation fault in SFML when i try to draw an sf::Text object

我在一个学校项目中使用 SFML,当我尝试 运行 这段代码时遇到了这个问题,我收到错误:双重释放或损坏 (out) 并且程序崩溃。我的操作系统是 ubuntu.

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

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

事件循环

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

根据SFML tutorials

A mistake that people often make is to forget the event loop, simply because they don't yet care about handling events (they use real-time inputs instead). Without an event loop, the window will become unresponsive. It is important to note that the event loop has two roles: in addition to providing events to the user, it gives the window a chance to process its internal events too, which is required so that it can react to move or resize user actions.

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

#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

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