Re: references and pointers
From: James Dennett (jdennett_at_acm.org)
Date: 02/23/04
- Next message: Josh Sebastian: "Re: Strategies for avoiding new?"
- Previous message: Sam of California: "Re: Some Advice."
- In reply to: Sam of California: "Re: references and pointers"
- Next in thread: Mike Wahler: "Re: references and pointers"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sun, 22 Feb 2004 17:52:43 -0800
Sam of California wrote:
> "Artie Gold" <artiegold@austin.rr.com> wrote in message
> news:c0f5l9$15q5j5$1@ID-219787.news.uni-berlin.de...
>
>>A reference cannot be NULL (so you don't have to check for that to
>>program robustly).
>
>
> So is the following invalid?
Your code is "invalid" -- specifically, it invokes
undefined behavior by referencing a null pointer.
> My VC 6 compiler accepts it; the value it
> outputs is "00000000" for "&a".
VC6 is quite allowed to do that, or to print
"error in program", or to do anything else.
>
> // - - - - - - - - -
> void Referrence(int &a) {
> cout << "Address: " << &a << '\n';
> return;
> }
That's a perfectly reasonable function, modulo
the spelling mistake in its name, which will
write the address of an int to cout (presumably
a stream, most likely ::std::cout).
> // - - - - - - - - -
>
> int main(int argc, char* argv[], char *envp[]) {
Note that the envp part of this is a non-standard
extension, and not really needed; std::getenv can
be used to read from the environment.
> int &r = *((int *)NULL);
There you dereference a null pointer, which is not
permitted. Anything goes.
> Referrence(r);
> return 0;
> }
Hope this clarifies -- there is no way to get a "null"
reference in a valid program. By the time your check
for a "null" reference might catch something, it's too
late.
-- James.
- Next message: Josh Sebastian: "Re: Strategies for avoiding new?"
- Previous message: Sam of California: "Re: Some Advice."
- In reply to: Sam of California: "Re: references and pointers"
- Next in thread: Mike Wahler: "Re: references and pointers"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|