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

Is c easy to learn?

552


Disadvantages of C language.

649


please explain clearly about execution of c program in detail,in which stage are the printf sacnf getting into exeecutable code

1701


The process of repeatedly running a set of computer instructions until some condition is specifed a) condition b) sequential condition c) global d) iteration

624


How can I write data files which can be read on other machines with different word size, byte order, or floating point formats?

607






What are comments and how do you insert it in a C program?

735


what are the advantages of a macro over a function?

639


What are the functions to open and close the file in c language?

589


How many identifiers are there in c?

575


Are negative numbers true in c?

595


Process by which one bit pattern in to another by bit wise operation is?

610


struct screen_pos{ int row, col } ;move_right(cursor)struct screen_pos *cursor;{ cursor.col++; } /* This statementhas a syntax error */What is the correct statement a) cursor.col = cursor.col + 1; b) col.cursor++; c) *cursor.col++; d) pointer

761


What are c preprocessors?

670


What is self-referential structure in c programming?

652


Write a program to print ASCII code for a given digit.

679