Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: do I need to free the pointer inside function?

Tags:

c++

pointers

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; 
}
like image 242
ArtificiallyIntelligence Avatar asked Oct 20 '25 13:10

ArtificiallyIntelligence


2 Answers

No.

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.

like image 99
Remy Lebeau Avatar answered Oct 23 '25 03:10

Remy Lebeau


There is no need to free any pointer as you are not doing any dynamic memory allocation here.

like image 42
rahul gupta Avatar answered Oct 23 '25 03:10

rahul gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!