C/delete

Advertisement


Question


hello sir

i he problem in this code
Q------>1.
int *p,x;
x=5;
p=&x;
cout<<*p;  // ist
delete(p);
cout << *p; // iind


in both the cases ist and iind stmt print correct value
even after delete operation ? is this is the problem of memory leak or something else ?

Q-------> 2
int *ptr=5;
is this is valid stmt , or if yes then 5 will store where ? we havent give any storage area or it takes storage from any where

make it clear ?

thank you
monika

Answer
Looks like your pointers basics is not yet clear!

1. Here you are doing delete() without performing new().
  Only if you did a new() before, delete() will be valid.
  But, your computer will not be able to tell whether the call is valid or not.
  It would have maintained a linked list of addresses that you have allocated using new().
  So, when you do delete(), it may refer that list and delete the address.
  Since you haven't done new(), the linked list is empty and hence delete() didn't do anything.

2. When you do:
int *ptr = 5;
  You are trying to assign the address 5 to ptr.
  This is just like:
int *ptr = (int *) malloc(1);
  If you do malloc (or new() in C++), the system will assign you a valid address from the heap.
  But, now you are doing your memory management and assigning 5 to ptr.
  So, it is your responsibility to see to it that, 5 is a valid address and is writable.
  Otherwise, your program will just do wrong things and will crash.

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Narendra

Expertise

I can answer questions in C related to programming, data structures, pointers and file manipulation. I use Solaris for doing C code and if you have questions related to C programming on Solaris, I will be able to help better.

Experience

6.5

Organizations belong to
Sun Microsystems

Awards and Honors
Brain Bench Certified Expert C programmer.
Advanced System Software Certified

©2012 About.com, a part of The New York Times Company. All rights reserved.