Search code examples
cmemorymallocfree

Pointer allocated in for: should I have to free it?


Let's suppose I have this code:

for (int i=0;i<n;i++) {
  //compute z
  float *p = (float *) malloc (sizeof(float)*z);
  //do something with p
}

Notice that p isn't used anywhere else and each for cycle is independent from the other.

Let's suppose that z is not so big, so the single p is not that expensive in terms of memmory. However, n is potentially big, so the total memory taken by p can be consistent.

Is it correct to free() it with:

for (int i=0;i<n;i++) {
  //compute z
  float *p = (float *) malloc (sizeof(float)*z);
  //do something with p
  free(p);
}

Bonus question: if time performance would be the priority (and not memory consumption), would be better to avoid the free(p), since it's time consuming?


Solution

  • Since you tagged this with C++, you should never use malloc and free. Use smart pointers (or new/delete if you don't have access to a C++11-compliant compiler).

    for (int i=0;i<n;i++) {
      // compute z
      std::unique_ptr<float[]> p{new float[z]};
      // do something with p
      // p gets automatically freed at the end of the scope
    }
    

    To answer your questions:

    Is it correct to free() it with...

    Yes. If you allocate something with malloc, you always need to free it.

    would be better to avoid the free(p), since it's time consuming?

    Yes. Consider preallocating the memory location outside of the loop.

    // preallocate
    std::unique_ptr<float[]> p{new float[z]};
    
    for (int i=0;i<n;i++) {
      // clear p
      // compute z
      // do something with p
    }
    
    // p gets automatically freed at the end of the scope