c – valgrind – Address —- is 0 bytes after a block of size 8 allocd

c – valgrind – Address —- is 0 bytes after a block of size 8 allocd

strcpy adds a null terminator character . 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 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.

I just had this message because I had changed a class (added a field, so I had changed its size) and not rebuilt all sources that included the header. So some modules still tried to use the old size.

c – valgrind – Address —- is 0 bytes after a block of size 8 allocd

Leave a Reply

Your email address will not be published.