Do I need to free the ptr? If so, how?
#include <iostream>
using namespace std;
void printFromPtr(int *ptr);
int main()
{
int a = 3;
int numPrint = 10000;
for (int i = 0; i < numPrint; i++)
{
printFromPtr(&a);
}
}
void printFromPtr(int* ptr)
{
cout << *ptr << endl;
}
The function is receiving a pointer from the caller, and does not know how the memory being pointed at was allocated, so it has no business trying to free it. Only the caller knows how it was allocated, so only the caller knows how to free it.
In this example, the caller is passing a pointer to a local variable a that is not allocated dynamically, so there is nothing to free manually. The variable will be gone when it goes out of scope.
There is no need to free any pointer as you are not doing any dynamic memory allocation here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With