int main()
{
int *p=new int;
*p=10;
del p;
cout<<*p;
*p= 60;
cout<<*p;
}
what will be the output & why?

Answer Posted / jaroosh

There will be an error because its "del" instead of "delete".
In this particular program, you might actually get away with
using p after delete, but lets look what happens here :

int *p=new int;
*p=10;
cout << "ADDRESS OF P is " << p << endl;
delete p;
int * x= new int(3);
cout << "ADDRESS OF X=" << *x << " is " << x << endl;
*p = 10; //We think we got away with deleting p so why not
//still use it!
cout << "VALUE OF X : " << *x; //Here is why...

now, though its basically a policy of compiler, here is what
probably WILL happen in the output (memory addresses are
exemplary):
ADDRESS OF P is 0x272740
ADDRESS OF X=3 is 0x272740
VALUE OF X : 10
Now this is totally NOT what we would like our program to
do, and this is because though delete WILL mostly call
objects destructors and sometimes even clear memory, but p
is STILL pointing to that location, to which compiler
assumes it is safe to allocate variable x!
So now we end up having ONE memory storage and two pointers
p and x pointing to it.
This is why though it will not crash your compilation and
probably you can get away with no runtime errors, this leads
to serious troubles and as a rule NEVER use pointers after
you deleted their storage.

Is This Answer Correct ?    7 Yes 1 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

In which language linux is written?

595


List the difference between a "copy constructor" and a "assignment operator"?

574


Why do we need volatile in c?

737


Wt are the Buses in C Language

2742


Is main is user defined function?

585






How can you convert integers to binary or hexadecimal?

607


Write a program to find the biggest number of three numbers in c?

584


What are reserved words with a programming language?

593


What are the 4 types of functions?

561


What does the characters “r” and “w” mean when writing programs that will make use of files?

847


Explain what are header files and explain what are its uses in c programming?

621


How can I write a function analogous to scanf?

643


What is a union?

601


Combinations of fibanocci prime series

1105


Is c a great language, or what?

596