I have this function:
int program_inc_capacity(Program *program)
{
Instruction *v_old = program->v;
size_t capacity_new = 2 * program->capacity;
program->v = (Instruction *)malloc(capacity_new * sizeof(Instruction));
if (program->v == NULL)
return 0;
for (size_t i = 0; i < program->size; i++)
{
program->v[i] = v_old[i];
}
free(v_old);
program->capacity = capacity_new;
return 1;
}
I call the above function when the memory previously allocated for program->v is no more enough. So I double it by reallocating the entire memory block through malloc.
Instead of using this approach I was thinking about using realloc()
.
So the code would look something like this:
int program_inc_capacity(Program *program)
{
Instruction *v_old = program->v;
size_t capacity_new = 2 * program->capacity;
Instruction *temp = (Instruction *)realloc(v_old, capacity_new * sizeof(Instruction));
if (temp == NULL) {
printf("Memory reallocation failed!\n");
free(v_old); // Free the original memory
return 1;
} else {
v_old = temp; // Update the pointer with the new memory location
}
for (size_t i = 0; i < program->size; i++)
{
program->v[i] = v_old[i];
}
free(v_old);
program->capacity = capacity_new;
return 1;
}
So, my question is: is there any performance difference? In which case is better the first approach over the second one and viceversa? I also read that using realloc many times can lead to memory fragmentation.
There seems to be quite a lot wrong with your use of realloc()
Why do you free(v_old);
on success?
You have not replaced program->v
realloc()
copies the data for you - if the reallocation was successful, you must not access the old pointer value.
The function always returns 1.
I suggest this simple re-write:
int program_inc_capacity(Program *program)
{
size_t capacity_new = 2 * program->capacity;
Instruction *temp = realloc(program->v, capacity_new * sizeof(Instruction));
if (temp == NULL) {
printf("Memory reallocation failed!\n");
return 1;
}
program->v = temp;
program->capacity = capacity_new;
return 0;
}