C++ reference and NULL

M

m.labanowicz

Hi,

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;
((void)(argv));
return bar(argc - 1, *ptr);
}

Which line do you expect that APP crashes ?

Regards
 
B

Barry Schwarz

Hi,

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;

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.
s_t * ptr = &local;

Given the next line, what purpose does the initialization serve? Or
why not initialize it to 0 immediately?
ptr = 0;
((void)(argv));

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.
return bar(argc - 1, *ptr);

Any attempt to dereference a NULL pointer invokes undefined behavior.
}

Which line do you expect that APP crashes ?

Undefined behavior is not guaranteed to crash the app.
 
J

Jorgen Grahn

(e-mail address removed) wrote: ....

This is the line that puzzles me.

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
 
L

Luca Risolia

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;
((void)(argv));
return bar(argc - 1, *ptr);
}

Which line do you expect that APP crashes ?

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

which is UB: the program will crash if you are lucky.
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,743
Latest member
WoodrowMea

Latest Threads

Top