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



  • Edit: moved to the General forum -- peppe

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

    foo();
    ~foo();

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

    private:

    };

    // foo.cpp
    foo::foo()
    {

    }

    foo::~foo()
    {

    }

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

    m_io.setDevice(&myfile);
    m_io.setByteOrder(QDataStream::BigEndian);
    
    return true;
    

    }

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

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

    my_foo.init("c:\some\file.dat");
    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.


  • Moderators

    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 :(@


  • Moderators

    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.


  • Moderators

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


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.