Important: Please read the Qt Code of Conduct -

I am a little curious about delete in Qt

  • I write the code in Qt Creator like this.
    int s;
    delete &s
    When I execute the code,there isn't any error message appear to me, and the program run still normally. But I try this code in MSVC, the program crashed. I don't know why? Can anybody explain this to me ? In my opinion, code like this should be illeagle. Has Qt lib handled the error, or something else?

  • I believe that the behaviour in this case is 'undefined' which means that the compiler can choose to do whatever it likes

  • This is nothing about Qt, it's only about C++ and the tool chain.

    I expect you tried it in QtCreator, right? with the default SDK, which means with minGW or on linux, it would be gcc.

    Delete just gets an address, what ever happens on that code, is undefined. When you say it crashed on MSVC, debug or release (which is a big difference, as debug builds in MSVC have a lot of checks).

  • Moderators

    bq. In my opinion, code like this should be illeagle [sic].

    Whether or not it's illegal, it's definitely a bad idea. :-)

  • Interesting code. I've never had the idea to do something crazy like that. Does anybody know what happens here in low-level detail? Aren't stack adresses in a different range than heap adresses such that the delete statement just doesn't do anything because it can't operate on stack? Or do the ranges overlap and the delete statement marks some corresponding memory block with the same adress on the heap as freed and crashes the application due to that?

  • The code I wrote is just for me to test. In fact, this code could be very easyly happened in Qt.Such as when your pass a QTableWidgetItem to setItem.
    QTableWidgetItem tableItem;
    In the document. Qt Helper doesn't forbid this usage with declaration. Indeed , There are no difference between them.

  • Moderators

    The documentation mentions that you should not allocate QObjects on the stack several times. I don't see what else we can do, since syntactically this is legal.

    If a programmer tries to rely on undefined behavior, then he/she is going to get bitten sooner or later.

  • [quote author="henryxuv" date="1346549695"]In fact, this code could be very easyly happened in Qt.Such as when your pass a QTableWidgetItem to setItem[/quote]

    Passing stack pointers to foreign functions should generally sound some alarm bells.

Log in to reply