c - 将 zSql arg 释放到 sqlite3_prepare_v2?

标签 c sqlite free

如果我有一个动态分配的字符串,其中包含我传递给 sqlite3_prepare_v2() 的查询,那么什么时候释放该字符串是安全的?紧接在 sqlite3_prepare_v2() 之后? sqlite3_step完成后?直到 sqlite3_finalize() 之后? nByte参数的值会影响答案吗?

最佳答案

来自documentation :

The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are recommended for all new programs. The two older interfaces are retained for backwards compatibility, but their use is discouraged. In the "v2" interfaces, the prepared statement that is returned (the sqlite3_stmt object) contains a copy of the original SQL text.

我相信这意味着您可以在调用 sqlite3_prepare_v2() 后立即安全地释放或修改字符串。

编辑:

沿着 sqlite3.c 代码进行短暂的浏览会发现这个小片段:

SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
  assert( isPrepareV2==1 || isPrepareV2==0 );
  if( p==0 ) return;
#ifdef SQLITE_OMIT_TRACE
  if( !isPrepareV2 ) return;
#endif
  assert( p->zSql==0 );
  p->zSql = sqlite3DbStrNDup(p->db, z, n);
  p->isPrepareV2 = (u8)isPrepareV2;
}

基本上,如果这是由 sqlite3_prepare_v2() 调用的,则会调用 strndup() 的一个版本来创建字符串的副本...

关于c - 将 zSql arg 释放到 sqlite3_prepare_v2?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11917073/

相关文章:

对 stdin、stdout 和 stderr 的工作方式感到困惑

c - 如何编写一个抛出 glibc 的自定义 free?

C 内存分配、结构数组中的段错误/双重释放

c - 有没有办法仅使用 malloc 和自由函数来更改数组大小?

C:打印宏的值

c - malloc typedef 指针

c - 如何在x86实模式ISR中将数据存储到全局变量中?

python - SqlAlchemy/Sqlite距离计算

sqlite - (没有这样的专栏).. 但是,它就在那里

sql - 来自复合键的索引是否足够?