lambgrp425
lambgrp425

Reputation: 706

Error while freeing a malloc'd array of structs

I'm having issues freeing a temporary array of structs used for doubling the size of another array. I don't seem to have any issues freeing the original array.

void foo(StruName **structName,i nt *size)
{ 
...
 StruName *temp_array = (StruName*) malloc(*size * 2 * sizeof(StruName));
 for (i = 0; i < *size; i++)
   temp_array[i] = (*original_array)[i];
 free(*original_array);
 *original_array = temp_array;
 free(*temp_array);

I get the following error using g++ -Wall

error: cannot convert ‘StruName’ to ‘void*’ for argument ‘1’ to ‘void free(void*)’

Any ideas what could be causing this? If I leave the free(*temp_array); out altogether, the program compiles and runs fine. free(temp_array); causes a segfault

Upvotes: 0

Views: 197

Answers (3)

user1222021
user1222021

Reputation:

What's the reason that original_array is a pointer to a pointer?

Anyways, it seems to me you shouldn't be freeing the temp array as your code snippet seems to imply you're replacing *original_array with it. If that's the case then you are working with freed memory; this might run fine for a while, but eventually you might find your array values get overwritten, as the freed memory gets reassigned to something else.

// here *original_array will be pointing to the new `malloc`ed memory
*original_array = temp_array;

// After this line, *original_array is left dangling to the recently freed memory

free(*temp_array);

I would remove that last free line.

*Edit * I previously mentioned the memory would be freed twice, this is not the case, as free should have been called without dereferencing *temp_array in order for that to be true.

Upvotes: 1

Daniel
Daniel

Reputation: 411

It's the basic principle of memory use that free what you have allocated. If you free what you haven't allocated, it might cause segmentfault.

The code have allocated the memory with:

    StruName *temp_array = (StruName*) malloc(*size * 2 * sizeof(StruName));

Then it should release the memory with:

    free(*temp_array);

Make sure the content of both parameters are correct.

Upvotes: 0

The following part of function definition is not correct :

void foo(Struct **structName, int count, int *size)

Have you declared your structure as structName? If yes, you need to mention the parameter as well in the definition, not just its type.And even if structName is your structure,then you are expected to write struct structName** instead of Struct **structName.(Struct is not the same as struct in C)

Here's one more error:

malloc(*size * 2 * sizeof(original_array)

You should enclose *size within braces as it's not clear whether you are dereferencing size or you are dereferencing the size*2*sizeof(original_array)

Upvotes: 2

Related Questions