'Why can't a function that has heap memory passed to it delete it in c++? [closed]
I tried to make a function that could delete memory on a int pointer. Unfortunately, it did not succeed. I feel like I made a mistake. Can someone help me find it?
#include <iostream>
void clean(int * x){
delete x;
x=nullptr;
}
int main() {
int * integer = new int;
clean(integer);
if(integer){
std::cout<<"Clean Failed\n";
}
else{
std::cout<<"Clean Succeeded\n";
}
}
Solution 1:[1]
Your clean function actually does deallocate the memory.
But it doesn't update the pointer passed to it.
Change clear to accept the pointer by refernce to fix the problem:
void clean(int *& x) {
delete x;
x = nullptr;
}
Some more information:
Parameters in C/C++ are actually always passed by value. In your original code, the pointer value (i.e. the address stored in it) is passed to clean.
When you change it to int *& x what is passed is a refernce to the pointer (which is actually similar semantic-wise to int ** x). I.e. it's the address of the pointer itself, not the address stored in it. Using the address of the pointer, the function clear can modify it and set it to nullptr.
Solution 2:[2]
Whenever something is passed to a function, it is copied to it.
Here, an int* is copied to clean.
Changing its value will not change it in the calling function.
Like this for example:
void func(int a) { ++a; }
int main() {
int a = 10;
func(a);
// a is still 10
return 0;
}
So you have to send a pointer to pointer to change its value. We use references in C++:
void clean(int*& x){
delete x;
x = nullptr;
}
clean(integer)
Which is internally:
void clean(int** x){
delete *x;
*x = nullptr;
}
clean(&integer)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | MisaghM |
