First, I know similar questions have been asked. However, I\'d like to have a more general simple question with really primitive C data types. So here it is.
In
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.
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.