Why does my program crash when the pointer is null? How can I check the stream>>? # Include "BBQ_Class.h"
# Include <iostream>
# Include <ostream>
# Include <istream>
# Include <string>
int main () (
Mine BBQ (12, 0, 0);
Sell BBQ (12, 0, 0);
mine.addBurger ();
yours.addHotDog (2);
Sell BBQ combo + = mine;
court <<"Here is the barbecue combined" <<endl;
* B1 = new BBQ grill (10, 0, 0);
* B2 = new BBQ grill (2, 0, 0);
court <<B1 <<"This is step 1" <<endl;
cin>> B1;
court <<B1 <<"this step if three prior endl NULL" <</ / see the change of values ...
B1 = NULL;
court <<B1 <<endl; / / be very careful ...
/ / Delete (b1) / / Why not this work?
delete (B2);
return 0;
)
/ / Functions
std:: ostream & operator <<(std:: ostream & out const, Barbecue & b) (
out <<b.myCapacity;
out <<b.myBurgers;
out <<b.myhotdogs;
return outs;
)
std:: ostream & operator <<(std:: ostream & out, const barbecue * b) (
return out <<B-> myCapacity <<""
<<B-myBurgers> <<""
<<b-> Myhotdogs ""
"Std:: endl;
)
std:: istream & operator>> (std:: istream & ins const, Barbecue & b) (
try (
* B = new BBQ grill (10, 3, 5);
)
catch (std:: logic_error le) (
)
int num;
ins>> num;
b.setCapacity (num);
return ins;
)
istream & operator>> (std:: istream & ins, const barbecue * b) (
try (
* B = new BBQ grill (10, 3, 5);
)
catch (std:: logic_error le) (
)
int count;
ins>> number;
b-setCapacity> (number);
return ins;
)
/ / Class BBQ (
friend std:: ostream & operator <<(std:: ostream & out const, Barbecue & b);
friend std:: ostream & operator <<(std:: ostream & out, const barbecue * b);
friend std:: istream & operator>> (std:: istream & ins const, Barbecue & b);
friend std:: istream & operator>> (std:: istream & ins, const barbecue * b);
I read in your code like this:
B1 = NULL;
/ / Delete (b1) / / Why not this work?
court <<B1 <<endl; / / be very careful ...
You should not put B1 = NULL until you do not need:
court <<B1 <<endl; / / be very careful
delete (b1) / / Now it should work
B1 = NULL; / / Now it is sure to be null
The reason is that the delete function all releases associated memory pointer to B1, which is, after the removal of B1, it points to an invalid address. So that's why you've finally set to null, which is also an invalid address, but is used to specify the pointer is no longer valid. So, strictly, it is not necessary to set it to zero, but it is convenient for the programmer.
Posted on June 4, 2010.