Allocating and freeing memory

Hello everyone!

Just to get this straight, suppose I have a loop that iterates some number of times. In each loop I allocate some array memory by declaring a pointer p and using the malloc function. Now, do I have to call free(p) at the very end of each iteration? Or is it that, when the loop finishes, memory automatically becomes deallocated?

Thanks for the help!
Last edited on
The former - the number of mallocs in a program should equal the number of frees. Those are typical C functions though - in C++ we tend to use 'new' and 'delete' instead. I'm sure there are edge cases, but this is the general rule.

Also, for ease of use, learn the STL:

1
2
3
4
5
6
for(int i = 0; i < 100; i++)
{
    unique_ptr<Shape> p = new Shape("Circle");
    // Do something with shape

} // auto deleted by unique_ptr! Handy, huh? 
Thank you for your reply.

I am familiar with STL and I couldn't be happier to use vector, by I'm working in a C environment at the moment.

Could you please reexplain this phrase: "The former - the number of mallocs in a program"?
All memory you allocate with malloc() must be freed via a call to free().
So the number of malloc calls has to match the number of free calls.
Or is it that, when the loop finishes, memory automatically becomes deallocated?


Yes, memory gets deallocated. BUT only the space taken by the pointer. Not the space the pointer points to.. so the object still needs to be freed....
The number of free can be greater than number of malloc if the pointer used in free is equal to zero.:)
@Jikax

This is exactly what I wanted to know. Thank you.


Thank you all.
Bjarne Stroustrup wrote:
Code that creates an object using new and then deletes it at the end of the same scope is ugly, error-prone, and inefficient.
Topic archived. No new replies allowed.