Cannot free fileName char * after fclose

239 views Asked by At

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.

3

There are 3 answers

4
Sourav Ghosh On BEST ANSWER

You code is having issue in the below line

strcat(*indexFileName, ".ind")

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()

... If dest (destination buffer) is not large enough, program behaviour is unpredictable;

So, once it invokes UB, there is no particular behaviour you can predict or expect.

That said,

  1. Please do not cast the return value of malloc() and family in C.

  2. sizeof(char) is guranteed to be 1 by C standard. You son't need to use that.

Solution [From the deleted answer by Mr. Mohit Jain]

Revise your allocation to:

int len = strlen(database) + strlen(".ind");   //allocate enough space to hold
*indexFileName = (char *)malloc(len + 1);      // the final concatenated string
0
LPs On

This

*indexFileName = (char *)malloc( len *sizeof(char) + 1);

must be

*indexFileName = (char *)malloc( len *sizeof(char) + 5);

due to the extention adding with

strcat(*indexFileName, ".ind")

0
Chirag Gangdev On

I suppose the problem is in "strcpy(*indexFileName, database);" instruction,

it should be strcpy(indexFileName, database);