delete error

it shows running error when i use delete memory but i dont know why please help

1
2
3
4
5
6
7
8
9
10
  int main()
{
	int num=5;
	int *ptrnum;
	ptrnum=#
   cout<<"*ptrnum"<<*ptrnum<<endl;
	delete ptrnum;
	cout<<"del ptrnum"<<*ptrnum<<endl;
	getch();
}
Your prtnum holds the address of literal constant 5. That memory location has not been dynamically allocated from heap with new and therefore cannot be deallocated either.
i used dynamic allocation using new but still it won't work could u help me out
What are you trying to accomplish?
I want to store value in pointer and than delete the value
> Your prtnum holds the address of literal constant 5.
Nope, ptrnum holds the address of num (look at line 5)
like in line 6 cout is *ptrnum:5 after deleting in line 7 why do i get an error in line 8 i want zero or delete any other junk value except 5
5 is as good junk value as any other.
Stop invoking undefined behaviour.
Yes you are right can i store value instead of adress in pointer and than delete the value and intialize a new value
You are storing the address of the variable 'num.' what you need to do insstead, since 'ptrnum' is already a pointer is this:
1
2
3
4
int num = 5;
int new*ptrnum;
ptrnum = num;
......
......
delete ptrnum;
Last edited on
Yes you are getting to my point but this causes synatx error like ptrnum undefined try it on ur compiler
Why do you have to "delete" a value?
To free memory and to practice the same thing for classes and structure and also to use this function to delete and store data for my phone book project
The logic structure should be:
1. Allocate memory
2. Use that memory
3. Release the memory


Show your latest implementation.
Thank you so much for help i appretiate it just one tiny thing could u implement this in simple code i tried it but i get syntax error or build errors i am bad at programming this will help me alot
Nevertheless, show your code.
1
2
3
4
5
	int  *ptr= new int;
	*ptr =5;
	cout<<5<<endl;
	delete ptr;
	cout<<ptr<<endl;

like now value is deleted why does it show adress shouldnt show junk value
Last edited on
You are not dereferencing the pointer

cout << *ptr << endl;
like now value is deleted why does it show adress shouldnt show junk value


Some common misconceptions about delete:

1) delete ptr; does not actually delete the pointer. It deletes the data that the pointer points to. When you do new int; you are creating a new unnamed integer... and then your 'ptr' pointer points to that integer. When you delete ptr you are deleting the unnamed integer, but are not changing 'ptr' at all.

2) Deleting a basic type like an int simply de-allcates memory. It does not [necessarily] fill that memory with garbage values. So it's very possible that the data will still be in that memory even after the data is deleted. Though it isn't guaranteed, as that memory may get allocated somewhere else and/or be overwritten by something else.
Topic archived. No new replies allowed.