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

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; 
}

Upvotes: 4

Views: 3184

Answers (5)

Gamindu Udayanga
Gamindu Udayanga

Reputation: 1

No.You have not allocated dynamic memory & no need to free the ptr.In your code ptr stores address of variable reside in the stack not the heap.

Upvotes: 0

You should use delete only for pointers obtained by new. Beware of dangling pointers and of memory leaks. Be very afraid of undefined behavior. And in C++ you should prefer smart pointers, see this (and use standard containers when convenient). And you generally don't use malloc and free in C++ (only in C). However many implementations of new are internally using malloc, etc...

Read also about the rule of five, and about RAII, about pointer aliasing, about virtual address space, about constructors and destructors, about virtual method tables. See this question.

Upvotes: 0

Jayesh Vyas
Jayesh Vyas

Reputation: 1351

when we are doing dynamic memory allocation then we need to free pointers.

Read this for more info

in your code you are passing pointer to local variable, so no need to free pointers.it will automatically remove(after reaching in out of scope.)

Upvotes: 1

Remy Lebeau
Remy Lebeau

Reputation: 596527

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.

Upvotes: 15

rahul gupta
rahul gupta

Reputation: 268

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

Upvotes: 4

Related Questions