I have an application which is used to modify content of a pdf file. Once the required changes are made , i save the file and quit the application. During this process i would like the clear the memory that has been assigned to the pdf file. The code is as given below:
for (i32 i = 0; i < job_state->PDF_IList_len; i++) {
if(IList[i].PIL_ImageData.PDH_DataPtr.PDH_PathName)
free (IList[i].PIL_ImageData.PDH_DataPtr.PDH_PathName);
if(IList[i].PIL_DependentImages)
free (IList[i].PIL_DependentImages);
}
job_state->PDF_ImageList = NULL;
job_state->PDF_context = NULL;
free (IList);
job_structure is a data structure to save info about the file.
PDH_Pathname is the temp directory where the details of the pdf is stored.
My application always crashes at
free (IList[i].PIL_ImageData.PDH_DataPtr.PDH_PathName);
I have noticed that whenever it crashes,the value for free (IList[i].PIL_ImageData.PDH_DataPtr.PDH_PathName) cannot be evaluated(thats what the debugger says).
If the for loop is commented out, there is no crash observed. Please let me know what can be the issue.
In addition to Als’ answer to use valgrind, it’s probably worth setting your pointers to
NULLafter you’ve freed them:free()doesn’t set pointers toNULL, it only releases the memory stored there. Since you’re testing the value of the pointer against zero to determine whether it needs to be freed, not setting the pointers toNULLcould be causing a double free if this code is called twice (or if anything insideIList[]points to a structure also encountered later in theIList[]).As per a comment, I’ve also removed the check against NULL before the free (as Joshua Green points out,
free(NULL)is perfectly safe).