Qt World Summit: Submit your Presentation

[Moved] [Solved] Crash when taking the address of local variables

  • Edit: moved to the General forum -- peppe

    @// foo.h
    class foo {
    QDataStream m_io;


    bool init(const QString filename);
    void check();



    // foo.cpp




    bool foo::init(const QString filename)
    QFile myfile(filename);
    if (!myfile.open(QIODevice::ReadWrite))
    return false;

    return true;


    void foo::check()
    qint32 mhead;
    m_io >> mhead; // this line causes a segfault :(

    // main.cpp
    int main()
    foo my_foo;

    my_foo.check(); // crash due to segfault

    return 0;

    It's seems to segfault whenever I try and access m_io in any other function than the one it was created in.

  • Is init() returning true or false?

    (Also, please use more descriptive titles for your threads.)

  • Sorry I really didn't know what to title it :( my bad.

    init returns true, and then steps into the other function, but then segfaults at @ m_io >> mhead; // this line causes a segfault :(@

  • You're creating the QFile on the stack in init(). It goes away after init() exits. The QDataStream is then pointing to an invalid QFile object internally, thus the crash.

    Move your QFile into your class definition as a member variable.

  • Oh man :s I didn't even think of that, thanks, works perfect.

  • No problem! Be sure and edit the title of the post to add [Solved] at the beginning. Thanks!

Log in to reply