Chironex
Chironex

Reputation: 819

Does C reuse memory after reassignment?

I'm writing a C program to calculate the path of a particle (similar to the three body problem). In my code I have typedef'ed structs to represent the particle, and a set of vectors to represent the particle's velocity, acceleration and position. As this is an iterative solution I have to recalculate all of these (and consequently malloc a new vector) thousands of times and reassign them to the parent struct in each iteration, like so:

while(collisionCheck(particle, mass0, mass1) == 0)
{
    particle-> velocity = recalculateVelocity(particle);
}

I'm concerned about how C will handle the orphaned struct, should I be freeing the old struct like this?

while(collisionCheck(particle, mass0, mass1) == 0)
{
    free(particle-> velocity);
    particle-> velocity = recalculateVelocity(particle);
}

Or will C garbage collect the orphans and reuse the memory space automatically?

Upvotes: 1

Views: 293

Answers (3)

Mario
Mario

Reputation: 36517

Only free particle->velocity if it's a pointer and recalculateVelocity() actually creates a new struct (or whatever) and returns the pointer to it.

If you're not using malloc(), you must not use free(). If you've used malloc(), you have to use free(). Only exception here is realloc().

Upvotes: 4

drrlvn
drrlvn

Reputation: 8437

C is not garbage collected, so it will not garbage collect anything. In order to free memory you must use the free() function after you've allocated with malloc().

So the answer is, if particle->velocity is the only pointer to space you've previously allocated with malloc(), you must release the memory with free() before you assign to that pointer, as that will mean you no longer have any pointer to that space, and that is a memory leak.

Upvotes: 3

BRPocock
BRPocock

Reputation: 13914

Well … C does not have any garbage collection.

For every memory region that you malloc, you're responsible for free:ing it, yourself.

However, once the memory has been freed, it will generally be re-used.

Upvotes: 4

Related Questions