delete pointer in other function

how to do it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;

void change(int *&p)
{	
	delete p;
	p=NULL;	
}

int main()
{
   
    int *pi= new int(35);
    
    cout << *pi<< endl;
    change(pi);
    cout << *pi<< endl;
 
    if(pi == NULL) cout << "its NULL";
    
    
}

i wanted to see "its NULL" output
You are doing it correctly. The problem is line 17 is trying to dereference a null pointer (since pi will be null at that point), and therefore your program is likely crashing.



Also note that you should never really do this. Allocated memory should have one clear owner. That is, the code responsible for allocating it is also responsible for destroying it. Passing around a pointer to other areas of code without a clear owner for it is very error prone and will likely lead to memory leaks or duplicate deletes, both of which are very bad.

Use a smart pointer (like std::unique_ptr) for dynamically allocated objects... or containers like std::vector for dynamically sized arrays. Very rarely (if ever) should you actually be managing memory yourself.
i am trying this because i need this in a linked list problem. please help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
using namespace std;

void change(int *&p) // or  *p ? **p ?
{
	*p=100;
	char c;
	cout << "want to delete here? y/n: ";
	cin >>c;
	if(c=='y')
	{
		delete p;
		cout << "deleted in change\n";	
	}	

}

int main()
{
   
    int *pi= new int(35);
    
    cout << *pi<< endl;
    change(pi);    
 
    if(pi != NULL)
    {
    	cout << "value = " << *pi << endl;
    	delete pi;
    	cout << "deleted in main\n";
    }   
	else cout << "deleted previously\n";
    
return 0;
}


output
35
want to delete here? y/n: y
deleted in change
value = 5439376

program exited at return value 25522352

how evaluate line 26 false?
Last edited on
closed account (SECMoG1T)
Hi Disch already told yah, let the memory allocated by some code be deallocated by the same code , deleting the pointers elsewhere can lead to serious bugs and undefined behavior, For application in linked list allocation and deallocation are better handled by a class interface, that way you would easily track your allocations and ddeallocations
got it.
thank you both.
Topic archived. No new replies allowed.