On Tue, Mar 18, 2008 at 04:06:04PM -0600, Dennis Cote scratched on the wall:
> Vincent Vega wrote:
> > query = sqlite3_mprintf("Insert into Inventory (Tag) values (?)");
>
> This allocates memory and saves a pointer to it in query.
My question is why use "sqlite3_mprintf()" at all? You're not
actually using any of the formatting functionality of _mprintf, only
passing a string literal which is then copied into a newly allocated
string. Since you're not modifying the string, there is no reason to
make a copy of it. The string literal you're passing to _mprintf is
going to be embedded into the application's memory space by the compiler.
There is no reason to not just pass the literal (or a reference to it)
directly to _prepare, which expects a const char* anyways.
Most compilers are even smart enough to combine multiple equivalent
string literals into a single reference, but just in case your compiler
is not, you can just setup a global var like this...
const char sql_insertInventory[] = "Insert into Inventory (Tag).... "
...and then reference the global var any time you need to reference the
actual query string. I tend to do this just to keep all the SQL string
literals in one place, which helps with updates and changes. It also
allows me to use symbolic names in the code, which is usually a good
thing.
In this case (since you're not changing the query string), it seems to
me that the best way to avoid leaking memory is not to allocate it in
the first place.
> > rc=sqlite3_prepare_v2(DB,query ,-1,&Statement,NULL);
If you do have some reason for using _mprintf to allocate "query", you
can/should de-allocate it right after this. Once the statement is
prepared, the literal SQL string is no longer needed. The
_prepare_v2 calls will keep a copy around, but everything I've seen
leads me to believe that this is a private copy that is released with
_finalize, and not something the user has to worry about.
(right?)
-j
--
Jay A. Kreibich < J A Y @ K R E I B I.C H >
"'People who live in bamboo houses should not throw pandas.' Jesus said that."
- "The Ninja", www.AskANinja.com, "Special Delivery 10: Pop!Tech 2006"
_______________________________________________
sqlite-users mailing list
[email protected]
http://sqlite.org:8080/cgi-bin/mailman/listinfo/sqlite-users