为什么 free 无法释放用于 sqlite3 错误的内存?

Why does free fail to dealloc memory used for sqlite3 errors?

提问人:misha 提问时间:7/9/2023 更新时间:7/9/2023 访问量:51

问:

我有一个简单的程序,可以打开并执行单个查询,它编译时没有任何错误或警告,但是当使用 valgrind 运行它时,它指出存在内存泄漏data.db

==1839== HEAP SUMMARY:
==1839==     in use at exit: 1,024 bytes in 1 blocks
==1839==   total heap usage: 215 allocs, 214 frees, 126,688 bytes allocated
==1839== 
==1839== 1,024 bytes in 1 blocks are definitely lost in loss record 1 of 1
==1839==    at 0x48407B4: malloc (vg_replace_malloc.c:381)
==1839==    by 0x109320: main (in /home/test/Desktop/sqlite_example/app)
==1839== 
==1839== LEAK SUMMARY:
==1839==    definitely lost: 1,024 bytes in 1 blocks
==1839==    indirectly lost: 0 bytes in 0 blocks
==1839==      possibly lost: 0 bytes in 0 blocks
==1839==    still reachable: 0 bytes in 0 blocks
==1839==         suppressed: 0 bytes in 0 blocks

这是生成内存泄漏的代码

int main()
{
    sqlite3 * db;
    char path[] = "data.db";
    int rc = sqlite3_open_v2(path, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, nullptr);
    if (rc != SQLITE_OK)
    {
        printf("Failed to open %s\n", path);
        return 1;
    }
    char sql[] = "CREATE TABLE IF NOT EXISTS  groups (group_id INTEGER PRIMARY KEY, name TEXT NOT NULL);";
    char * err = (char*)malloc(sizeof(char)*1024);
    rc = sqlite3_exec(db, sql, nullptr,nullptr,&err);

    if (rc != SQLITE_OK)
    {
        printf("Failed to execute query {%s}\n", sql);
        sqlite3_close(db);
        return 1;
    }
    free(err);
    sqlite3_close(db);
    return 0;
}

我检查了sqlite文档,有,但是使用它们也不能解决问题sqlite3_mallocsqlite3_free

C++ SQLite malloc valgrind

评论

3赞 tkausl 7/9/2023
不应为 .err
0赞 Igor Tandetnik 7/10/2023
sqlite3_exec不像你想象的那样工作。正确的用法是这样的:你不为 ;如有必要,该函数会执行,然后解除分配它。char* err = nullptr; sqlite3_exec(..., &err); DoSomethingWith(err); sqlite3_free(err);err
0赞 Igor Tandetnik 7/10/2023
在任何情况下,您按编写的程序都会泄漏该内存。只有在错误发生时才释放它,在这种情况下,无论如何都是 null。在出现错误并且会出现错误消息的情况下,您没有完全释放为错误消息分配的内存。为什么你甚至要传递最后一个参数,而你没有对错误消息做任何事情?您可以在那里传递 null。err

答: 暂无答案