SQLite User Forum

shell nit, goofy import leaks memory
Login

shell nit, goofy import leaks memory

(1.1) By Larry Brasfield (LarryBrasfield) on 2020-05-29 19:11:49 edited from 1.0 [source]

In this thread, I noted that the leak discovered and reported by its OP could be reproduced. I have since simplified the repro input and diagnosed where and why the leak occurs.

If sqlite3.exe (or any other platform's executable) is given this input:

.i  |junk (Not(SQL
.q

, the .import command handler will take an error exit whereby some memory held by the sCtx struct variable is never freed (except by process clean-up.) The exiting code, with an added statement (marked by 'NEW CODE ...' below) does not leak, which demonstrates the leak mechanism. Said code reads:

    sqlite3_free(zSql);
    if( rc ){
      if (pStmt) sqlite3_finalize(pStmt);
      utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
      xCloser(sCtx.in);
      sqlite3_free(sCtx.z); /* NEW CODE, copied from elsewhere in shell.c */
      rc = 1;
      goto meta_command_exit;
    }
    nCol = sqlite3_column_count(pStmt);

I hereby disclaim any and all rights to that added code, and acknowledge that it is merely a copy of the very same statement found in some nearby lines. This is not a patch; it is just a demonstration of how to plug one little leak.

The issue and code relate to SQLite v3.32.1 and many earlier versions.

(2) By anonymous on 2020-05-29 19:22:07 in reply to 1.0 [link] [source]

sqlite3_free(sCtx.z);

Just to add, this is needed before all goto meta_commad_exit; jumps in the span shell.c.in:8011-8136

(3) By Richard Hipp (drh) on 2020-05-29 19:54:28 in reply to 2 [link] [source]

(4) By anonymous on 2020-05-29 20:06:04 in reply to 3 [link] [source]

This seems to clear the leak, yet the build throws a warning.

shell.c:13450:23: warning: comparison of address of 'p->xCloser' not equal to a null pointer is always true [-Wtautological-pointer-compare]
  if( p->in!=0 &&& p->xCloser!=0 ){
                   ~~~^~~~~~~  ~

(5) By Andreas Kupries (andreas-kupries) on 2020-05-29 20:56:11 in reply to 4 [link] [source]

Why does the code have a triple & ? (&&&) I suspect that the compiler interprets that as && (logical and) followed by an & (address operator), applied to p->xCloser.