Home:ALL Converter>Error while freeing a malloc'd array of structs

Error while freeing a malloc'd array of structs

Ask Time:2013-04-28T06:48:02         Author:lambgrp425

Json Formatter

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

Author:lambgrp425,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/16257642/error-while-freeing-a-mallocd-array-of-structs
Rüppell's Vulture :

The following part of function definition is not correct :\n\nvoid foo(Struct **structName, int count, int *size)\n\n\nHave 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)\n\nHere's one more error:\n\nmalloc(*size * 2 * sizeof(original_array)\n\n\nYou 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)",
2013-04-27T22:52:02
user1222021 :

What's the reason that original_array is a pointer to a pointer?\n\nAnyways, 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\nworking 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. \n\n// here *original_array will be pointing to the new `malloc`ed memory\n*original_array = temp_array;\n\n// After this line, *original_array is left dangling to the recently freed memory\n\nfree(*temp_array);\n\n\nI would remove that last free line.\n\n*Edit *\nI 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.",
2013-04-27T23:40:39
yy