I am dynamically allocating memory at the beginning of a for using:
Candset_t* emptycandset(void) {
Candset_t* cset;
cset = (Candset_t*)malloc(sizeof(Candset_t));
cset->size = 0;
cset->maxsize = MAXSIZE;
cset->dptr = (Point_t*)malloc(MAXSIZE * sizeof(Point_t));
return cset;
}
whereby Candset and Point_t are both typedef. later I free the memory at the end of the loop with:
void destroycandset(Candset_t* cset) {
free(cset->dptr);
free(cset);
}
The reason why I am doing this is because I want to reuse the same variable(memory space) in all the iterations of the loop. This actually cause fragmentation of the heap. Hence, decreased performance. How can I solve this? is it possible to reinitiate a dynamically allocated space? How does this affect the dynamic memory? Cheers
I am trying to reuse a dynamically allocated memory. However, using malloc and free cause fragmentation of the heap. Do you know any way to avoid memory fragmentation?
typedef struct point {
double x, y;
unsigned int dst;
} Point_t;
typedef struct candset {
unsigned int size;
unsigned int maxsize;
Point_t* dptr;
} Candset_t;
This is what the struct data look like.
I can't tell what the size of the dptr
and Candset_t
will be; Hence, I have to allocate them dynamically. It make no difference when using new
and delete
for c++ only.
For structures smaller than 1 MB whose lifetime is simple, don't use dynamic allocation at all.
Just create a
Candset_t
in automatic storage (on the stack).Automatic storage provides memory extremely efficiently.
If your object is "simple" enough to malloc-and-modify, it is also free to create in automatic storage.
There are people who are used to languages like Java or C#, where creating an object is inherently expensive.
In C++, creating an object can be literally free. It can also be expensive. How expensive it is depends on the properties of the object.
Because objects in C++ carry less baggage than in garbage collected languages, the "free" case is really, really free.
To make an object effectively free to use, ensure that it doesn't use dynamically allocated memory at construction time, and to be extra sure avoid virtual functions (sometimes these can also be free). Next, don't use
new
ormalloc
to create it.Here is a simple "free" class:
so long as MAXSIZE isn't really big, like in the many 1000s, this is going to be a better plan than the original.
If this doesn't work, then you can just move the declaration of
Candset_t
up a scope, and reuse it. You do not want to reallocatedptr
, but instead write code to clear the memory in it.Generally, calls to
malloc
ornew
take 100x or more the time of a typical line of C++ code. So avoid them in tight loops.