int main()
{
int *p=new int;
*p=10;
del p;
cout<<*p;
*p= 60;
cout<<*p;
}
what will be the output & why?
Answers were Sorted based on User's Feedback
Answer / sethuu
First output will print some garbage value because you
delete the object p and the you print.
The second one will print value 60.
Is This Answer Correct ? | 11 Yes | 3 No |
Answer / 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 |
Answer / hemang
There will be error because del is used instead of delete. in c++ delete is the keyword not del. delete is used to delete an object.
So program will not run....
Is This Answer Correct ? | 6 Yes | 0 No |
Answer / anu
I think error will come bcoz memory allocated to *P is
already deleted d it will point to nowhere now....
Is This Answer Correct ? | 3 Yes | 5 No |
Is c programming hard?
Why do some versions of toupper act strangely if given an upper-case letter?
what is c
what is the difference between #include<> and #include”…”?
Why do we use namespace feature?
main() { int l=6; switch(l) { default:l=l+2; case 4:l=4; case 5:l++; break; } printf("%d",l); }
How many ways are there to swap two numbers without using temporary variable? Give the each logic.
1.write a program to merge the arrays 2.write efficient code for extracting unique elements from a sorted list of array?
What does typeof return in c?
int x=5; printf("%d%d%d",x,x<<2,x>>2);
What is a 'null pointer assignment' error?
A woman had somany gloves and hats 22 red,34 blue, 45 white...there was power cut and she took a glove and how many gloves shud she take so that she gets a pair of glove fr each color??