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
How will you print TATA alone from TATA POWER using string copy and concate commands in C?
Explain what could possibly be the problem if a valid function name such as tolower() is being reported by the c compiler as undefined?
When I tried to go into a security sites I am denied access and a message appeared saying 'applet not initialize'. How can I rectify this problem.
Is c still used?
general for is %wd,f-d; in this system "w" means a) 'w' represent total width of digits b) 'w' represent width which includes the digits before,after decimal place and the decimal point c) 'w' represent width which includes the digits before only d) 'w' represent width after decimal place only
What is the best organizational structure?
What is the function of volatile in c language?
Which header file is essential for using strcmp function?
Difference between linking and loading?
What does != Mean in c?
ATM machine and railway reservation class/object diagram
What is sorting in c plus plus?
Why doesnt the call scanf work?
If you know then define #pragma?
What is a good way to implement complex numbers in c?