I am trying to free my file name (char *
pointer) but got an error :
Heap corruption detected: after normal block (#65) at 0x....
The code:
static FILE *initializeIndexFile(char *database, char **indexFileName)
{
FILE *file1_p;
*indexFileName = NULL;
int len = strlen(database);
*indexFileName = (char *)malloc(len *sizeof(char) + 1);
strcpy(*indexFileName, database);
file1_p = fopen(strcat(*indexFileName, ".ind"), "rb");
if (file1_p == NULL)
Handle_Failure();
fclose(file1_p);
free(*indexFileName);
return file1_p;
}
Firstly I tought it because the file is still open so I make fclose()
calling but still its got the same error.
You code is having issue in the below line
the destination buffer at
*indexFileName
is having insufficient memory to hold the concatenated string. Hence it invokes undefined behaviour.From the man page of
strcat()
So, once it invokes UB, there is no particular behaviour you can predict or expect.
That said,
Please do not cast the return value of
malloc()
and family inC
.sizeof(char)
is guranteed to be1
byC
standard. You son't need to use that.Solution [From the deleted answer by Mr. Mohit Jain]
Revise your allocation to: