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

前端 未结 1 491
名媛妹妹
名媛妹妹 2021-02-11 20:28

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

1条回答
  •  借酒劲吻你
    2021-02-11 20:59

    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.

    0 讨论(0)
提交回复
热议问题