提问人:misha 提问时间:7/9/2023 更新时间:7/9/2023 访问量:51
为什么 free 无法释放用于 sqlite3 错误的内存?
Why does free fail to dealloc memory used for sqlite3 errors?
问:
我有一个简单的程序,可以打开并执行单个查询,它编译时没有任何错误或警告,但是当使用 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_malloc
sqlite3_free
答: 暂无答案
评论
err
sqlite3_exec
不像你想象的那样工作。正确的用法是这样的:你不为 ;如有必要,该函数会执行,然后解除分配它。char* err = nullptr; sqlite3_exec(..., &err); DoSomethingWith(err); sqlite3_free(err);
err
err