Is there a memory leak in the normal sqlite3 _ * () routine?
The usual procedure sqlite3_prepare_v2 () + sqlite3_step () + sqlite3_finalize () may contain a leak.
Sounds funny. But the test code seems to be talking about it. Or I was using sqlite3 _ * () incorrectly.
Appreciate any answer.
#include <stdio.h>
#include <unistd.h> // for usleep()
#include <sqlite3.h>
int multi_write (int j);
sqlite3 *db = NULL;
int main (void)
{
int ret = -1;
ret = sqlite3_open("test.db", &db);
ret = sqlite3_exec(db,"CREATE TABLE data_his (id INTEGER PRIMARY KEY, d1 CHAR(16))", NULL,NULL,NULL);
usleep (100000);
int j=0;
while (1)
{
multi_write (j++);
usleep (2000000);
printf (" ----------- %d\n", j);
}
ret = sqlite3_close (db);
return 0;
}
int multi_write (int j)
{
int ret = -1;
char *sql_f = "INSERT OR REPLACE INTO data_his VALUES (%d, %Q)";
char *sql = NULL;
sqlite3_stmt *p_stmt = NULL;
ret = sqlite3_prepare_v2 (db, "BEGIN TRANSACTION", -1, &p_stmt, NULL);
ret = sqlite3_step ( p_stmt );
ret = sqlite3_finalize ( p_stmt );
int i=0;
for (i=0; i<100; i++)
{
sql = sqlite3_mprintf ( sql_f, j*100000 + i, "00000000000068FD");
ret = sqlite3_prepare_v2 (db, sql, -1, &p_stmt, NULL );
sqlite3_free ( sql );
//printf ("sqlite3_prepare_v2(): %d, %s\n", ret, sqlite3_errmsg (db));
ret = sqlite3_step ( p_stmt );
//printf ("sqlite3_step(): %d, %s\n", ret, sqlite3_errmsg (db));
ret = sqlite3_finalize ( p_stmt );
//printf ("sqlite3_finalize(): %d, %s\n\n", ret, sqlite3_errmsg (db));
}
ret = sqlite3_prepare_v2 (db, "COMMIT TRANSACTION", -1, &p_stmt, NULL );
ret = sqlite3_step ( p_stmt );
ret = sqlite3_finalize ( p_stmt );
return 0;
}
And I watch the process start from the top.
Memory statistics first:
PID PPID USER STAT VSZ %MEM %CPU COMMAND
17731 15488 root S 1104 5% 7% ./sqlite3multiwrite
When printf () while (1) {} from main () prints 150, the memory statistics are:
PID PPID USER STAT VSZ %MEM %CPU COMMAND
17731 15488 root S 1552 5% 7% ./sqlite3multiwrite
It sounds like after 150 memory cycles the memory used by sqlite3multiwrite increases from 1104KB to 1552KB.
What does it mean? memory leak or some other thing?
a source to share
Use Valgrind. The growth from 1.1MB to 1.5MB isn't that big, especially over 150 iterations. SQLite can do some caching for example (it reserves memory in advance).
Try more iterations - there may be a threshold that your program cannot grow by. But Valgrind is the most accurate tool for finding memory leaks.
a source to share
I got a key answer from http://old.nabble.com/Is-there-any-memory-leak-in-the-normal-routine--td28348648.html#a28354683
Sqlite3 cache is the reason ::
a source to share