C++ reference and NULL

Discussion in 'C++' started by m.labanowicz, Mar 19, 2014.

  1. m.labanowicz

    m.labanowicz Guest


    There is interesting example about NULL and reference usage in C++ :)

    typedef struct {
    int a [2];
    } s_t;
    int bar(int v, s_t &s) {
    return v ? s.a[0] : 0;
    int main(int argc, char * argv []) {
    s_t local;
    s_t * ptr = &local;
    ptr = 0;
    return bar(argc - 1, *ptr);

    Which line do you expect that APP crashes ?

    m.labanowicz, Mar 19, 2014
    1. Advertisements

  2. The contents of local are indeterminate. Even if you passed local to
    bar() by reference, which you don't, the evaluation of local.a[0]
    would cause undefined behavior.
    Given the next line, what purpose does the initialization serve? Or
    why not initialize it to 0 immediately?
    What purpose does this line serve? argv is a pointer guaranteed to
    have a valid value. Evaluating that address and then discarding the
    result is effectively a no-op.
    Any attempt to dereference a NULL pointer invokes undefined behavior.
    Undefined behavior is not guaranteed to crash the app.
    Barry Schwarz, Mar 19, 2014
    1. Advertisements

  3. m.labanowicz

    Jorgen Grahn Guest

    You see it in C code sometimes ... it makes at least gcc shut up
    about possibly unused parameters.

    I cannot explain the extra pairs of () though.

    Jorgen Grahn, Mar 19, 2014
  4. m.labanowicz

    Luca Risolia Guest

    $ cppcheck main.cpp
    Checking main.cpp...
    [main.cpp:12]: (error) Null pointer dereference

    which is UB: the program will crash if you are lucky.
    Luca Risolia, Mar 22, 2014
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.