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.