-2

I am new to C++ and am curious..

Why does this compile but crash at runtime:

 wxBitmap *bmp;
*bmp = wxNullBitmap;   //wxNullBitmap is type wxBitmap with null data

when this would compile and run fine:

  wxBitmap bmp;
  bmp = wxNullBitmap;

Isn't it the same thing??

user1489223
  • 153
  • 1
  • 8
  • See [Where exactly does C++ standard say dereferencing an uninitialized pointer is undefined behavior?](http://stackoverflow.com/questions/4285895) – Drew Dormann Apr 29 '16 at 22:16

1 Answers1

2

Pointer is address of memory. In first example, you create pointer but it's value is undefined. Where does it point to? And then you try to copy your objects to some random, undefined location in memory. OS doesn't let you to do it.

George Sovetov
  • 4,942
  • 5
  • 36
  • 57
  • 2
    "Pointer is address of memory" in typical implementation, but not necessary. – MikeCAT Apr 29 '16 at 22:07
  • I see. I guess I was thinking that the command wxBitmap *bmp; would create a space in memory for a wxBitmap object itself. so you need to use "*bmp=new wxBitmap()" to create the memory location? – user1489223 Apr 30 '16 at 00:30
  • @user1489223 Yes. `new` allocates memory and calls constructor. Don't forget to use `delete` when you don't need it anymore. – George Sovetov Apr 30 '16 at 05:05