Hello, I am wondering whether I am freeing the the memory correctly or is there a better way to do so. Please enlighten me anyone. Much appreciated.
Here is my data.
Code:
struct CSVRow
{
char** colData;
int size;
};
struct CSVData
{
struct CSVRow* rowData;
int size;
};
Here is the free memory function. I want to free everything. Am i doing this right?
Code:
/* Deallocates all entries of the given CSV Data */
void FreeCSVData(struct CSVData* target)
{
/* variable declarations */
int rowSize = 0, colSize = 0, i = 0, j = 0;
/* checks for invalid input parameter */
if (target == NULL)
return;
/* assign the row size of target to variable rowSize */
rowSize = target->size;
/* loop through the rows of CSVData */
for (i = 0; i < rowSize; i++)
{
/* assign the row size of target to variable rowSize */
colSize = target->rowData[i].size;
/* loop through the column section of each specific rows */
for (j = 0; j < colSize; j++)
{
/* assigning each column data with null */
target->rowData[i].colData[j] = NULL;
/* free each column data */
free(target->rowData[i].colData[j]);
}
/* assigning each row of column data with null */
target->rowData[i].colData = NULL;
/* free each row of column data */
free(target->rowData[i].colData);
}
/* lastly free all rows */
free(target->rowData);
/* notify upon success function execution */
printf("Free CSVData success!\n");
return;
}
Assuming you're working on the heap, no! You're assigning NULL before you call free. You end up calling free with NULL as the memory pointer to free. You need to switch those two operations and free the memory before you invalidate the pointers. You should also invalidate your rowData pointer to possibly avoid dangling pointers.
Originally Posted by Biesi
Assuming you're working on the heap, no! You're assigning NULL before you call free. You end up calling free with NULL as the memory pointer to free. You need to switch those two operations and free the memory before you invalidate the pointers. You should also invalidate your rowData pointer to possibly avoid dangling pointers.
Oh no.. I never knew that, I always thought that it is the opposite. Now it makes sense. Thank you!
Other than that, I hope I am not causing anymore leaks.
Originally Posted by faid
I hope I am not causing anymore leaks.
Handling memory in C is a very complex topic that also depends on how you allocated the memory.. if you're working on the stack, you're mostly just fine, otherwise every allocate call should correspond to a free call.