Search code examples
cstringmemorymallocfree

Why cant I free the char buffer after assigning the last index to null terminator (\0)


I'm just confused as to why this keeps giving me an error.

If I just fread the file in and don't assign the last index to the null terminator, I can free the memory after using it. However, if I do assign the last index to the null terminator and try to free the data after using it, I get an error.

char *readFileToString(const char *file)
{
    char * buffer = 0;
    long length;
    FILE * f = fopen (file, "rb");

    if(f == NULL) 
        printf("ERROR::FILE:FILE_NOT_SUCCESFULLY_READ\n");

    fseek (f, 0, SEEK_END);
    length = ftell (f);
    fseek (f, 0, SEEK_SET);
    buffer = malloc (length);
    if(buffer == NULL) printf("Error alocating buffer memory");
    fread (buffer, 1, length, f);
    fclose (f);
    buffer[length] = '\0'; // Offending line <------------------ code works if we don't do this

    return buffer;
}

int main()
{
    char *t = readFileToString("test");
    printf("%s", t);

    free(t); // ERROR IF WE CHANGE LAST BUFFER CHARACTER TO null terminator
}

Solution

  • Arrays are indexed from 0 in C language.

    • valid range of indexes: [0, length -1]

    buffer[length] = 0; invokes undefined behaviour as you access the element which is outside of the array bounds.

    Side note:

    Your check:

    if(buffer == NULL) printf("Error alocating buffer memory");
    

    does not prevent accessing the NULL pointer. You need to change the program flow

    if(buffer == NULL) 
    {
      printf("Error alocating buffer memory");
      return NULL;
    }