valgrind - Address ---- is 0 bytes after a block of size 8 alloc'd

strcpy adds a null terminator character '\0'. You forgot to allocate space for it:

*filename = (char*)realloc(*filename, strlen(*collection_name)*sizeof(char)+5);

You need to add space for 5 characters: 4 for ".tde" suffix, and one more for the '\0' terminator. Your current code allocates only 4, so the last write is done into the space immediately after the block that you have allocated for the new filename (i.e. 0 bytes after it).

Note: Your code has a common problem - it assigns the results of realloc directly to a pointer being reallocated. This is fine when realloc is successful, but creates a memory leak when it fails. Fixing this error requires storing the result of realloc in a separate variable, and checking it for NULL before assigning the value back to *filename:

char *tmp = (char*)realloc(*filename, strlen(*collection_name)*sizeof(char)+5);
if (tmp != NULL) {
    *filename = tmp;
} else {
    // Do something about the failed allocation
}

Assigning directly to *filename creates a memory leak, because the pointer the *filename has been pointing to below would become overwritten on failure, becoming non-recoverable.

Tags:

Linux

C

Valgrind