home bbs files messages ]

Forums before death by AOL, social media and spammers... "We can't have nice things"

   comp.lang.c++.moderated      Moderated discussion of C++ superhackery      33,346 messages   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]

   Message 33,129 of 33,346   
   Edward Diener to kawninzx6@googlemail.com   
   Re: dynamic_cast undefined behavior   
   20 Jul 13 00:23:13   
   
   From: eldiener@tropicsoft.invalid   
      
   On 7/19/2013 8:02 PM, kawninzx6@googlemail.com wrote:   
   > Hi C++ experts,   
   >   
   > Is it ever safe to dereference a NULL pointer?  Specifically,   
   > I'm curious about dereferencing NULL during dynamic_cast.   
   >   
   > Contrived example code:   
   > // includes omitted   
   >   
   > class BaseFoo   
   > {   
   >    public:   
   >      virtual ~BaseFoo() {}   
   > };   
   >   
   > class Foo : public BaseFoo {};   
   >   
   > void process(int& i) { ... }   
   >   
   > void process(Foo& foo) { ... }   
   >   
   > BaseFoo* getFoo() { ... }   
      
   I assume you meant:   
      
   BaseFoo* getFoo() { return 0; }   
      
   >   
   > int main()   
   > {   
   >    int *i = NULL;   
   >    void process(*i); // (1)   
      
   That's not safe. You will probably get an OS exception at run-time for   
   trying to read memory at 0.   
      
   >   
   >    try   
   >    {   
   >      process(dynamic_cast(*getFoo())); // (2)   
      
   That's not safe also. Ditto with the above.   
      
   >    }   
   >    catch (const std::exception&)   
   >    {   
   >      // ignore bad_cast exception   
   >    }   
   >   
   >    return 0;   
   > }   
   >   
   > (1) - This is always undefined behavior, right?   
   > (2) - Does this dynamic_cast produce undefined behavior if   
   >        getFoo() returns a NULL pointer?   
   >   
   > If it matters, I'm not using C++11.   
      
   Neither are safe and both invoke undefined behavior. C++ doesn't tell   
   the OS what to do but an operating system exception for accessing memory   
   at 0 normally occurs in my experience.   
      
      
   --   
         [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
         [ comp.lang.c++.moderated.    First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]


(c) 1994,  bbs@darkrealms.ca