Debian Codegraph @

www/malloc.html

raw
1 <!DOCTYPE html>
2 <html><head>
3 <meta name="viewport" content="width=device-width, initial-scale=1.0">
4 <meta http-equiv="content-type" content="text/html; charset=UTF-8">
5 <link href="sqlite.css" rel="stylesheet">
6 <title>Dynamic Memory Allocation In SQLite</title>
7 <!-- path= -->
8 </head>
9 <body>
10 <div class=nosearch>
11 <a href="index.html">
12 <img class="logo" src="images/sqlite370_banner.gif" alt="SQLite" border="0">
13 </a>
14 <div><!-- IE hack to prevent disappearing logo --></div>
15 <div class="tagline desktoponly">
16 Small. Fast. Reliable.<br>Choose any three.
17 </div>
18 <div class="menu mainmenu">
19 <ul>
20 <li><a href="index.html">Home</a>
21 <li class='mobileonly'><a href="javascript:void(0)" onclick='toggle_div("submenu")'>Menu</a>
22 <li class='wideonly'><a href='about.html'>About</a>
23 <li class='desktoponly'><a href="docs.html">Documentation</a>
24 <li class='desktoponly'><a href="download.html">Download</a>
25 <li class='wideonly'><a href='copyright.html'>License</a>
26 <li class='desktoponly'><a href="support.html">Support</a>
27 <li class='desktoponly'><a href="prosupport.html">Purchase</a>
28 <li class='search' id='search_menubutton'>
29 <a href="javascript:void(0)" onclick='toggle_search()'>Search</a>
30 </ul>
31 </div>
32 <div class="menu submenu" id="submenu">
33 <ul>
34 <li><a href='about.html'>About</a>
35 <li><a href='docs.html'>Documentation</a>
36 <li><a href='download.html'>Download</a>
37 <li><a href='support.html'>Support</a>
38 <li><a href='prosupport.html'>Purchase</a>
39 </ul>
40 </div>
41 <div class="searchmenu" id="searchmenu">
42 <form method="GET" action="search">
43 <select name="s" id="searchtype">
44 <option value="d">Search Documentation</option>
45 <option value="c">Search Changelog</option>
46 </select>
47 <input type="text" name="q" id="searchbox" value="">
48 <input type="submit" value="Go">
49 </form>
50 </div>
51 </div>
52 <script>
53 function toggle_div(nm) {
54 var w = document.getElementById(nm);
55 if( w.style.display=="block" ){
56 w.style.display = "none";
57 }else{
58 w.style.display = "block";
59 }
60 }
61 function toggle_search() {
62 var w = document.getElementById("searchmenu");
63 if( w.style.display=="block" ){
64 w.style.display = "none";
65 } else {
66 w.style.display = "block";
67 setTimeout(function(){
68 document.getElementById("searchbox").focus()
69 }, 30);
70 }
71 }
72 function div_off(nm){document.getElementById(nm).style.display="none";}
73 window.onbeforeunload = function(e){div_off("submenu");}
74 /* Disable the Search feature if we are not operating from CGI, since */
75 /* Search is accomplished using CGI and will not work without it. */
76 if( !location.origin || !location.origin.match || !location.origin.match(/http/) ){
77 document.getElementById("search_menubutton").style.display = "none";
78 }
79 /* Used by the Hide/Show button beside syntax diagrams, to toggle the */
80 function hideorshow(btn,obj){
81 var x = document.getElementById(obj);
82 var b = document.getElementById(btn);
83 if( x.style.display!='none' ){
84 x.style.display = 'none';
85 b.innerHTML='show';
86 }else{
87 x.style.display = '';
88 b.innerHTML='hide';
89 }
90 return false;
91 }
92 var antiRobot = 0;
93 function antiRobotGo(){
94 if( antiRobot!=3 ) return;
95 antiRobot = 7;
96 var j = document.getElementById("mtimelink");
97 if(j && j.hasAttribute("data-href")) j.href=j.getAttribute("data-href");
98 }
99 function antiRobotDefense(){
100 document.body.onmousedown=function(){
101 antiRobot |= 2;
102 antiRobotGo();
103 document.body.onmousedown=null;
104 }
105 document.body.onmousemove=function(){
106 antiRobot |= 2;
107 antiRobotGo();
108 document.body.onmousemove=null;
109 }
110 setTimeout(function(){
111 antiRobot |= 1;
112 antiRobotGo();
113 }, 100)
114 antiRobotGo();
115 }
116 antiRobotDefense();
117 </script>
118 <div class=fancy>
119 <div class=nosearch>
120 <div class="fancy_title">
121 Dynamic Memory Allocation In SQLite
122 </div>
123 <div class="fancy_toc">
124 <a onclick="toggle_toc()">
125 <span class="fancy_toc_mark" id="toc_mk">&#x25ba;</span>
126 Table Of Contents
127 </a>
128 <div id="toc_sub"><div class="fancy-toc1"><a href="#_features">1. Features</a></div>
129 <div class="fancy-toc1"><a href="#_testing">2. Testing</a></div>
130 <div class="fancy-toc2"><a href="#_use_of_reallocarray_">2.1. Use of reallocarray()</a></div>
131 <div class="fancy-toc1"><a href="#_configuration">3. Configuration</a></div>
132 <div class="fancy-toc2"><a href="#_alternative_low_level_memory_allocators">3.1. Alternative low-level memory allocators</a></div>
133 <div class="fancy-toc3"><a href="#the_default_memory_allocator">3.1.1. The default memory allocator</a></div>
134 <div class="fancy-toc3"><a href="#the_debugging_memory_allocator">3.1.2. The debugging memory allocator</a></div>
135 <div class="fancy-toc3"><a href="#the_win32_native_memory_allocator">3.1.3. The Win32 native memory allocator</a></div>
136 <div class="fancy-toc3"><a href="#zero_malloc_memory_allocator">3.1.4. Zero-malloc memory allocator</a></div>
137 <div class="fancy-toc3"><a href="#experimental_memory_allocators">3.1.5. Experimental memory allocators</a></div>
138 <div class="fancy-toc3"><a href="#application_defined_memory_allocators">3.1.6. Application-defined memory allocators</a></div>
139 <div class="fancy-toc3"><a href="#memory_allocator_overlays">3.1.7. Memory allocator overlays</a></div>
140 <div class="fancy-toc3"><a href="#no_op_memory_allocator_stub">3.1.8. No-op memory allocator stub</a></div>
141 <div class="fancy-toc2"><a href="#_page_cache_memory">3.2. Page cache memory</a></div>
142 <div class="fancy-toc2"><a href="#_lookaside_memory_allocator">3.3. Lookaside memory allocator</a></div>
143 <div class="fancy-toc3"><a href="#two_size_lookaside">3.3.1. Two-Size Lookaside</a></div>
144 <div class="fancy-toc2"><a href="#_memory_status">3.4. Memory status</a></div>
145 <div class="fancy-toc2"><a href="#_setting_memory_usage_limits">3.5. Setting memory usage limits</a></div>
146 <div class="fancy-toc1"><a href="#_mathematical_guarantees_against_memory_allocation_failures">4. Mathematical Guarantees Against Memory Allocation Failures</a></div>
147 <div class="fancy-toc2"><a href="#_computing_and_controlling_parameters_m_and_n">4.1. Computing and controlling parameters M and n</a></div>
148 <div class="fancy-toc2"><a href="#_ductile_failure">4.2. Ductile failure</a></div>
149 <div class="fancy-toc1"><a href="#_stability_of_memory_interfaces">5. Stability Of Memory Interfaces</a></div>
150 </div>
151 </div>
152 <script>
153 function toggle_toc(){
154 var sub = document.getElementById("toc_sub")
155 var mk = document.getElementById("toc_mk")
156 if( sub.style.display!="block" ){
157 sub.style.display = "block";
158 mk.innerHTML = "&#x25bc;";
159 } else {
160 sub.style.display = "none";
161 mk.innerHTML = "&#x25ba;";
162 }
163 }
164 </script>
165 </div>
166
167
168
169
170
171 <h1 style="margin-left:1.0em" notoc="1" id="overview"> Overview</h1>
172
173 <p>SQLite uses dynamic memory allocation to obtain
174 memory for storing various objects
175 (ex: <a href="c3ref/sqlite3.html">database connections</a> and <a href="c3ref/stmt.html">prepared statements</a>) and to build
176 a memory cache of the database file and to hold the results of queries.
177 Much effort has gone into making the dynamic memory allocation subsystem
178 of SQLite reliable, predictable, robust, secure, and efficient.</p>
179
180 <p>This document provides an overview of dynamic memory allocation within
181 SQLite. The target audience is software engineers who are tuning their
182 use of SQLite for peak performance in demanding environments.
183 Nothing in this document is required knowledge for using SQLite. The
184 default settings and configuration for SQLite will work well in most
185 applications. However, the information contained in this document may
186 be useful to engineers who are tuning SQLite to comply with special
187 requirements or to run under unusual circumstances.</p>
188
189 <a name="features"></a>
190 <h1 id="_features"><span>1. </span> Features</h1>
191
192 <p>The SQLite core and its memory allocation subsystem provides the
193 following capabilities:</p>
194
195 <ul>
196 <li><p>
197 <b>Robust against allocation failures.</b>
198 If a memory allocation ever fails (that is to say,
199 if malloc() or realloc() ever return NULL)
200 then SQLite will recover gracefully. SQLite will first attempt
201 to free memory from unpinned cache pages then retry the allocation
202 request.
203 Failing that, SQLite will either stop what
204 it is doing and return the
205 <a href="rescode.html#nomem">SQLITE_NOMEM</a> error code back up to the application or it will
206 make do without the requested memory.
207 </p></li>
208
209 <li><p>
210 <b>No memory leaks.</b>
211 The application is responsible for destroying any objects it allocates.
212 (For example, the application must use <a href="c3ref/finalize.html">sqlite3_finalize()</a> on
213 every <a href="c3ref/stmt.html">prepared statement</a> and <a href="c3ref/close.html">sqlite3_close()</a> on every
214 <a href="c3ref/sqlite3.html">database connection</a>.) But as long as
215 the application cooperates, SQLite will never leak memory. This is
216 true even in the face of memory allocation failures or other system
217 errors.
218 </p></li>
219
220 <li><p>
221 <b>Memory usage limits.</b>
222 The <a href="c3ref/hard_heap_limit64.html">sqlite3_soft_heap_limit64()</a> mechanism allows the application to
223 set a memory usage limit that SQLite strives to stay below. SQLite
224 will attempt to reuse memory from its caches rather than allocating new
225 memory as it approaches the soft limit.
226 </p></li>
227
228 <li><p>
229 <b>Zero-malloc option.</b>
230 The application can optionally provide SQLite with several buffers of bulk memory
231 at startup and SQLite will then use those provided buffers for all of
232 its memory allocation needs and never call system malloc() or free().
233 </p></li>
234
235 <li><p>
236 <b>Application-supplied memory allocators.</b>
237 The application can provide SQLite with pointers to alternative
238 memory allocators at start-time. The alternative memory allocator
239 will be used in place of system malloc() and free().
240 </p></li>
241
242 <li><p>
243 <b>Proof against breakdown and fragmentation.</b>
244 SQLite can be configured so that, subject to certain usage constraints
245 detailed below, it is guaranteed to never fail a memory allocation
246 or fragment the heap.
247 This property is important to long-running, high-reliability
248 embedded systems where a memory allocation error could contribute
249 to an overall system failure.
250 </p></li>
251
252 <li><p>
253 <b>Memory usage statistics.</b>
254 Applications can see how much memory they are using and detect when
255 memory usage is approaching or exceeding design boundaries.
256 </p></li>
257
258 <a name="pwwo"></a>
259 <li><p>
260 <b>Plays well with memory debuggers.</b>
261 Memory allocation in SQLite is structured so that standard
262 third-party memory debuggers (such as <a href="http://dmalloc.com">dmalloc</a> or
263 <a href="http://valgrind.org">valgrind</a>) can be used to verify correct
264 memory allocation behavior.</p>
265
266 </li><li><p>
267 <b>Minimal calls to the allocator.</b>
268 The system malloc() and free() implementations are inefficient
269 on many systems. SQLite strives to reduce overall processing time
270 by minimizing its use of malloc() and free().
271 </p></li>
272
273 <li><p>
274 <b>Open access.</b>
275 Pluggable SQLite extensions or even the application itself can
276 access to the same underlying memory allocation
277 routines used by SQLite through the
278 <a href="c3ref/free.html">sqlite3_malloc()</a>, <a href="c3ref/free.html">sqlite3_realloc()</a>, and <a href="c3ref/free.html">sqlite3_free()</a> interfaces.
279 </p></li>
280
281 </ul>
282
283 <a name="testing"></a>
284 <h1 id="_testing"><span>2. </span> Testing</h1>
285
286 <p>Most of the code in the SQLite source tree is devoted purely to
287 <a href="testing.html">testing and verification</a>. Reliability is important to SQLite.
288 Among the tasks of the test infrastructure is to ensure that
289 SQLite does not misuse dynamically allocated memory, that SQLite
290 does not leak memory, and that SQLite responds
291 correctly to a dynamic memory allocation failure.</p>
292
293 <p>The test infrastructure verifies that SQLite does not misuse
294 dynamically allocated memory by using a specially instrumented
295 memory allocator. The instrumented memory allocator is enabled
296 at compile-time using the <a href="compile.html#memdebug">SQLITE_MEMDEBUG</a> option. The instrumented
297 memory allocator is much slower than the default memory allocator and
298 so its use is not recommended in production. But when
299 enabled during testing,
300 the instrumented memory allocator performs the following checks:</p>
301
302 <ul>
303 <li><p><b>Bounds checking.</b>
304 The instrumented memory allocator places sentinel values at both ends
305 of each memory allocation to verify that nothing within SQLite writes
306 outside the bounds of the allocation.</p></li>
307
308 <li><p><b>Use of memory after freeing.</b>
309 When each block of memory is freed, every byte is overwritten with a
310 nonsense bit pattern. This helps to ensure that no memory is ever
311 used after having been freed.</p></li>
312
313 <li><p><b>Freeing memory not obtained from malloc.</b>
314 Each memory allocation from the instrumented memory allocator contains
315 sentinels used to verify that every allocation freed came
316 from prior malloc.</p></li>
317
318 <li><p><b>Uninitialized memory.</b>
319 The instrumented memory allocator initializes each memory allocation
320 to a nonsense bit pattern to help ensure that the user makes no
321 assumptions about the content of allocation memory.</p></li>
322 </ul>
323
324 <p>Regardless of whether or not the instrumented memory allocator is
325 used, SQLite keeps track of how much memory is currently checked out.
326 There are hundreds of test scripts used for testing SQLite. At the
327 end of each script, all objects are destroyed and a test is made to
328 ensure that all memory has been freed. This is how memory
329 leaks are detected. Notice that memory leak detection is in force at
330 all times, during test builds and during production builds. Whenever
331 one of the developers runs any individual test script, memory leak
332 detection is active. Hence memory leaks that do arise during development
333 are quickly detected and fixed.</p>
334
335 <a name="oomtesting"></a>
336 <p>The response of SQLite to out-of-memory (OOM) errors is tested using
337 a specialized memory allocator overlay that can simulate memory failures.
338 The overlay is a layer that is inserted in between the memory allocator
339 and the rest of SQLite. The overlay passes most memory allocation
340 requests straight through to the underlying allocator and passes the
341 results back up to the requester. But the overlay can be set to
342 cause the Nth memory allocation to fail. To run an OOM test, the overlay
343 is first set to fail on the first allocation attempt. Then some test
344 script is run and verification that the allocation was correctly caught
345 and handled is made. Then the overlay is set to fail on the second
346 allocation and the test repeats. The failure point continues to advance
347 one allocation at a time until the entire test procedure runs to
348 completion without hitting a memory allocation error. This whole
349 test sequence run twice. On the first pass, the
350 overlay is set to fail only the Nth allocation. On the second pass,
351 the overlay is set to fail the Nth and all subsequent allocations.</p>
352
353 <p>Note that the memory leak detection logic continues to work even
354 when the OOM overlay is being used. This verifies that SQLite
355 does not leak memory even when it encounters memory allocation errors.
356 Note also that the OOM overlay can work with any underlying memory
357 allocator, including the instrumented memory allocator that checks
358 for memory allocation misuse. In this way it is verified that
359 OOM errors do not induce other kinds of memory usage errors.</p>
360
361 <p>Finally, we observe that the instrumented memory allocator and the
362 memory leak detector both work over the entire SQLite test suite and
363 the <a href="testing.html#tcl">TCL test suite</a> provides over 99% statement test coverage and that
364 the <a href="th3.html">TH3</a> test harness provides <a href="testing.html#coverage">100% branch test coverage</a>
365 with no leak leaks. This is
366 strong evidence that dynamic memory allocation is used correctly
367 everywhere within SQLite.</p>
368
369 <a name="allocarray"></a>
370 <h2 id="_use_of_reallocarray_"><span>2.1. </span> Use of reallocarray()</h2>
371
372 <p>The reallocarray() interface is a recent innovation (circa 2014)
373 from the OpenBSD community that grow out of efforts to prevent the
374 next <a href="http://heartbleed.com">"heartbleed" bug</a> by avoiding 32-bit integer
375 arithmetic overflow on memory allocation size computations. The
376 reallocarray() function has both unit-size and count parameters.
377 To allocate memory sufficient to hold an array of N elements each X-bytes
378 in size, one calls "reallocarray(0,X,N)". This is preferred over
379 the traditional technique of invoking "malloc(X*N)" as reallocarray()
380 eliminates the risk that the X*N multiplication will overflow and
381 cause malloc() to return a buffer that is a different size from what
382 the application expected.</p>
383
384 <p>SQLite does not use reallocarray(). The reason is that reallocarray()
385 is not useful to SQLite. It turns out that SQLite never does memory
386 allocations that are the simple product of two integers. Instead, SQLite
387 does allocations of the form "X+C" or "N*X+C" or "M*N*X+C" or
388 "N*X+M*Y+C", and so forth. The reallocarray() interface is not helpful
389 in avoiding integer overflow in those cases.</p>
390
391 <p>Nevertheless, integer overflow in the computation of memory allocation
392 sizes is a concern that SQLite would like to deal with. To prevent
393 problems, all SQLite internal memory allocations occur using thin wrapper
394 functions that take a signed 64-bit integer size parameter. The SQLite
395 source code is audited to ensure that all size computations are carried
396 out using 64-bit signed integers as well. SQLite will
397 refuse to allocate more than about 2GB of memory at one go. (In common
398 use, SQLite seldom ever allocates more than about 8KB of memory at a time
399 so a 2GB allocation limit is not a burden.) So the 64-bit size parameter
400 provides lots of headroom for detecting overflows. The same audit that
401 verifies that all size computations are done as 64-bit signed integers
402 also verifies that it is impossible to overflow a 64-bit integer
403 during the computation.</p>
404
405 <p>The code audits used to ensure that memory allocation size computations
406 do not overflow in SQLite are repeated prior to every SQLite release.</p>
407
408 <a name="config"></a>
409 <h1 id="_configuration"><span>3. </span> Configuration</h1>
410
411 <p>The default memory allocation settings in SQLite are appropriate
412 for most applications. However, applications with unusual or particularly
413 strict requirements may want to adjust the configuration to more closely
414 align SQLite to their needs.
415 Both compile-time and start-time configuration options are available.</p>
416
417 <a name="altalloc"></a>
418
419 <h2 id="_alternative_low_level_memory_allocators"><span>3.1. </span> Alternative low-level memory allocators</h2>
420
421 <p>The SQLite source code includes several different memory allocation
422 modules that can be selected at compile-time, or to a limited extent
423 at start-time.</p>
424
425 <a name="defaultalloc"></a>
426
427 <h3 id="the_default_memory_allocator"><span>3.1.1. </span>The default memory allocator</h3>
428
429 <p>By default, SQLite uses the malloc(), realloc(), and free() routines
430 from the standard C library for its memory allocation needs. These routines
431 are surrounded by a thin wrapper that also provides a "memsize()" function
432 that will return the size of an existing allocation. The memsize() function
433 is needed to keep an accurate count of the number of bytes of outstanding
434 memory; memsize() determines how many bytes to remove from the outstanding
435 count when an allocation is freed. The default allocator implements
436 memsize() by always allocating 8 extra bytes on each malloc() request and
437 storing the size of the allocation in that 8-byte header.</p>
438
439 <p>The default memory allocator is recommended for most applications.
440 If you do not have a compelling need to use an alternative memory
441 allocator, then use the default.</p>
442
443 <a name="memdebug"></a>
444
445 <h3 id="the_debugging_memory_allocator"><span>3.1.2. </span>The debugging memory allocator</h3>
446
447 <p>If SQLite is compiled with the <a href="compile.html#memdebug">SQLITE_MEMDEBUG</a> compile-time option,
448 then a different, heavy wrapper is used around system malloc(), realloc(),
449 and free().
450 The heavy wrapper allocates around 100 bytes of extra space
451 with each allocation. The extra space is used to place sentinel values
452 at both ends of the allocation returned to the SQLite core. When an
453 allocation is freed,
454 these sentinels are checked to make sure the SQLite core did not overrun
455 the buffer in either direction. When the system library is GLIBC, the
456 heavy wrapper also makes use of the GNU backtrace() function to examine
457 the stack and record the ancestor functions of the malloc() call. When
458 running the SQLite test suite, the heavy wrapper also records the name of
459 the current test case. These latter two features are useful for
460 tracking down the source of memory leaks detected by the test suite.</p>
461
462 <p>The heavy wrapper that is used when <a href="compile.html#memdebug">SQLITE_MEMDEBUG</a> is set also
463 makes sure each new allocation is filled with nonsense data prior to
464 returning the allocation to the caller. And as soon as an allocation
465 is free, it is again filled with nonsense data. These two actions help
466 to ensure that the SQLite core does not make assumptions about the state
467 of newly allocated memory and that memory allocations are not used after
468 they have been freed.</p>
469
470 <p>The heavy wrapper employed by <a href="compile.html#memdebug">SQLITE_MEMDEBUG</a> is intended for use
471 only during testing, analysis, and debugging of SQLite. The heavy wrapper
472 has a significant performance and memory overhead and probably should not
473 be used in production.</p>
474
475 <a name="win32heap"></a>
476
477 <h3 id="the_win32_native_memory_allocator"><span>3.1.3. </span>The Win32 native memory allocator</h3>
478
479 <p>If SQLite is compiled for Windows with the <a href="compile.html#win32_malloc">SQLITE_WIN32_MALLOC</a>
480 compile-time option, then a different, thin wrapper is used around
481 HeapAlloc(), HeapReAlloc(), and HeapFree(). The thin wrapper uses the
482 configured SQLite heap, which will be different from the default process
483 heap if the <a href="compile.html#win32_heap_create">SQLITE_WIN32_HEAP_CREATE</a> compile-time option is used. In
484 addition, when an allocation is made or freed, HeapValidate() will be
485 called if SQLite is compiled with assert() enabled and the
486 <a href="compile.html#win32_malloc_validate">SQLITE_WIN32_MALLOC_VALIDATE</a> compile-time option.</p>
487
488 <a name="memsys5"></a>
489
490 <h3 id="zero_malloc_memory_allocator"><span>3.1.4. </span>Zero-malloc memory allocator</h3>
491
492 <p>When SQLite is compiled with the <a href="compile.html#enable_memsys5">SQLITE_ENABLE_MEMSYS5</a> option, an
493 alternative memory allocator that does not use malloc() is included in the
494 build. The SQLite developers refer to this alternative memory allocator
495 as "memsys5". Even when it is included in the build, memsys5 is
496 disabled by default.
497 To enable memsys5, the application must invoke the following SQLite
498 interface at start-time:</p>
499
500 <blockquote><pre>
501 <a href="c3ref/config.html">sqlite3_config</a>(<a href="c3ref/c_config_covering_index_scan.html#sqliteconfigheap">SQLITE_CONFIG_HEAP</a>, pBuf, szBuf, mnReq);
502 </pre></blockquote>
503
504 <p>In the call above, pBuf is a pointer to a large, contiguous chunk
505 of memory space that SQLite will use to satisfy all of its memory
506 allocation needs. pBuf might point to a static array or it might
507 be memory obtained from some other application-specific mechanism.
508 szBuf is an integer that is the number of bytes of memory space
509 pointed to by pBuf. mnReq is another integer that is the
510 minimum size of an allocation. Any call to <a href="c3ref/free.html">sqlite3_malloc(N)</a> where
511 N is less than mnReq will be rounded up to mnReq. mnReq must be
512 a power of two. We shall see later that the mnReq parameter is
513 important in reducing the value of <b>n</b> and hence the minimum memory
514 size requirement in the <a href="malloc.html#nofrag">Robson proof</a>.</p>
515
516 <p>The memsys5 allocator is designed for use on embedded systems,
517 though there is nothing to prevent its use on workstations.
518 The szBuf is typically between a few hundred kilobytes up to a few
519 dozen megabytes, depending on system requirements and memory budget.</p>
520
521 <p>The algorithm used by memsys5 can be called "power-of-two,
522 first-fit". The sizes of all memory allocation
523 requests are rounded up to a power of two and the request is satisfied
524 by the first free slot in pBuf that is large enough. Adjacent freed
525 allocations are coalesced using a buddy system. When used appropriately,
526 this algorithm provides mathematical guarantees against fragmentation and
527 breakdown, as described further <a href="#nofrag">below</a>.</p>
528
529 <a name="memsysx"></a>
530
531 <h3 id="experimental_memory_allocators"><span>3.1.5. </span>Experimental memory allocators</h3>
532
533 <p>The name "memsys5" used for the zero-malloc memory allocator implies
534 that there are several additional memory allocators available, and indeed
535 there are. The default memory allocator is "memsys1". The debugging
536 memory allocator is "memsys2". Those have already been covered.</p>
537
538 <p>If SQLite is compiled with <a href="compile.html#enable_memsys3">SQLITE_ENABLE_MEMSYS3</a> then another
539 zero-malloc memory allocator, similar to memsys5, is included in the
540 source tree. The memsys3 allocator, like memsys5, must be activated
541 by a call to <a href="c3ref/config.html">sqlite3_config</a>(<a href="c3ref/c_config_covering_index_scan.html#sqliteconfigheap">SQLITE_CONFIG_HEAP</a>,...). Memsys3
542 uses the memory buffer supplied as its source for all memory allocations.
543 The difference between memsys3 and memsys5 is that memsys3 uses a
544 different memory allocation algorithm that seems to work well in
545 practice, but which does not provide mathematical
546 guarantees against memory fragmentation and breakdown. Memsys3 was
547 a predecessor to memsys5. The SQLite developers now believe that
548 memsys5 is superior to
549 memsys3 and that all applications that need a zero-malloc memory
550 allocator should use memsys5 in preference to memsys3. Memsys3 is
551 considered both experimental and deprecated and will likely be removed
552 from the source tree in a future release of SQLite.</p>
553
554 <p>Memsys4 and memsys6 were experimental memory allocators
555 introduced in around 2007 and subsequently removed from the
556 source tree in around 2008, after it became clear that they
557 added no new value.</p>
558
559 <p>Other experimental memory allocators might be added in future releases
560 of SQLite. One may anticipate that these will be called memsys7, memsys8,
561 and so forth.</p>
562
563 <a name="appalloc"></a>
564 <h3 id="application_defined_memory_allocators"><span>3.1.6. </span>Application-defined memory allocators</h3>
565
566 <p>New memory allocators do not have to be part of the SQLite source tree
567 nor included in the sqlite3.c <a href="amalgamation.html">amalgamation</a>. Individual applications can
568 supply their own memory allocators to SQLite at start-time.</p>
569
570 <p>To cause SQLite to use a new memory allocator, the application
571 simply calls:</p>
572
573 <blockquote><pre>
574 <a href="c3ref/config.html">sqlite3_config</a>(<a href="c3ref/c_config_covering_index_scan.html#sqliteconfigmalloc">SQLITE_CONFIG_MALLOC</a>, pMem);
575 </pre></blockquote>
576
577 <p>In the call above, pMem is a pointer to an <a href="c3ref/mem_methods.html">sqlite3_mem_methods</a> object
578 that defines the interface to the application-specific memory allocator.
579 The <a href="c3ref/mem_methods.html">sqlite3_mem_methods</a> object is really just a structure containing
580 pointers to functions to implement the various memory allocation primitives.
581 </p>
582
583 <p>In a multi-threaded application, access to the <a href="c3ref/mem_methods.html">sqlite3_mem_methods</a>
584 is serialized if and only if <a href="c3ref/c_config_covering_index_scan.html#sqliteconfigmemstatus">SQLITE_CONFIG_MEMSTATUS</a> is enabled.
585 If <a href="c3ref/c_config_covering_index_scan.html#sqliteconfigmemstatus">SQLITE_CONFIG_MEMSTATUS</a> is disabled then the methods in
586 <a href="c3ref/mem_methods.html">sqlite3_mem_methods</a> must take care of their own serialization needs.</p>
587
588 <a name="overlayalloc"></a>
589 <h3 id="memory_allocator_overlays"><span>3.1.7. </span>Memory allocator overlays</h3>
590
591 <p>An application can insert layers or "overlays" in between the
592 SQLite core and the underlying memory allocator.
593 For example, the <a href="#oomtesting">out-of-memory test logic</a>
594 for SQLite uses an overlay that can simulate memory allocation
595 failures.</p>
596
597 <p>An overlay can be created by using the</p>
598
599 <blockquote><pre>
600 <a href="c3ref/config.html">sqlite3_config</a>(<a href="c3ref/c_config_covering_index_scan.html#sqliteconfiggetmalloc">SQLITE_CONFIG_GETMALLOC</a>, pOldMem);
601 </pre></blockquote>
602
603 <p>interface to obtain pointers to the existing memory allocator.
604 The existing allocator is saved by the overlay and is used as
605 a fallback to do real memory allocation. Then the overlay is
606 inserted in place of the existing memory allocator using
607 the <a href="c3ref/config.html">sqlite3_config</a>(<a href="c3ref/c_config_covering_index_scan.html#sqliteconfigmalloc">SQLITE_CONFIG_MALLOC</a>,...) as described
608 <a href="#appalloc">above</a>.
609
610 <a name="stuballoc"></a>
611 </p><h3 id="no_op_memory_allocator_stub"><span>3.1.8. </span>No-op memory allocator stub</h3>
612
613 <p>If SQLite is compiled with the <a href="compile.html#zero_malloc">SQLITE_ZERO_MALLOC</a> option, then
614 the <a href="malloc.html#defaultalloc">default memory allocator</a> is omitted and replaced by a stub
615 memory allocator that never allocates any memory. Any calls to the
616 stub memory allocator will report back that no memory is available.</p>
617
618 <p>The no-op memory allocator is not useful by itself. It exists only
619 as a placeholder so that SQLite has a memory allocator to link against
620 on systems that may not have malloc(), free(), or realloc() in their
621 standard library.
622 An application that is compiled with <a href="compile.html#zero_malloc">SQLITE_ZERO_MALLOC</a> will need to
623 use <a href="c3ref/config.html">sqlite3_config()</a> together with <a href="c3ref/c_config_covering_index_scan.html#sqliteconfigmalloc">SQLITE_CONFIG_MALLOC</a> or
624 <a href="c3ref/c_config_covering_index_scan.html#sqliteconfigheap">SQLITE_CONFIG_HEAP</a> to specify a new alternative memory allocator
625 before beginning to use SQLite.</p>
626
627 <a name="pagecache"></a>
628
629 <h2 id="_page_cache_memory"><span>3.2. </span> Page cache memory</h2>
630
631 <p>In most applications, the database page cache subsystem within
632 SQLite uses more dynamically allocated memory than all other parts
633 of SQLite combined. It is not unusual to see the database page cache
634 consume over 10 times more memory than the rest of SQLite combined.</p>
635
636 <p>SQLite can be configured to make page cache memory allocations from
637 a separate and distinct memory pool of fixed-size
638 slots. This can have two advantages:</p>
639
640 <ul>
641 <li><p>
642 Because allocations are all the same size, the memory allocator can
643 operate much faster. The allocator need not bother with coalescing
644 adjacent free slots or searching for a slot
645 of an appropriate size. All unallocated memory slots can be stored on
646 a linked list. Allocating consists of removing the first entry from the
647 list. Deallocating is simply adding an entry to the beginning of the list.
648 </p></li>
649
650 <li><p>
651 With a single allocation size, the <b>n</b> parameter in the
652 <a href="malloc.html#nofrag">Robson proof</a> is 1, and the total memory space required by the allocator
653 (<b>N</b>) is exactly equal to maximum memory used (<b>M</b>).
654 No additional memory is required to cover fragmentation overhead, thus
655 reducing memory requirements. This is particularly important for the
656 page cache memory since the page cache constitutes the largest component
657 of the memory needs of SQLite.
658 </p></li>
659 </ul>
660
661 <p>The page-cache memory allocator is disabled by default.
662 An application can enable it at start-time as follows:</p>
663
664 <blockquote><pre>
665 <a href="c3ref/config.html">sqlite3_config</a>(<a href="c3ref/c_config_covering_index_scan.html#sqliteconfigpagecache">SQLITE_CONFIG_PAGECACHE</a>, pBuf, sz, N);
666 </pre></blockquote>
667
668 <p>The pBuf parameter is a pointer to a contiguous range of bytes that
669 SQLite will use for page-cache memory allocations. The buffer must be
670 at least sz*N bytes in size. The "sz" parameter
671 is the size of each page-cache allocation. N is the maximum
672 number of available allocations.</p>
673
674 <p>If SQLite needs a page-cache entry that is larger than "sz" bytes or
675 if it needs more than N entries, it falls back to using the
676 general-purpose memory allocator.</p>
677
678 <a name="lookaside"></a>
679
680 <h2 id="_lookaside_memory_allocator"><span>3.3. </span> Lookaside memory allocator</h2>
681
682 <p>SQLite <a href="c3ref/sqlite3.html">database connections</a> make many
683 small and short-lived memory allocations.
684 This occurs most commonly when compiling SQL statements using
685 <a href="c3ref/prepare.html">sqlite3_prepare_v2()</a> but also to a lesser extent when running
686 <a href="c3ref/stmt.html">prepared statements</a> using <a href="c3ref/step.html">sqlite3_step()</a>. These small memory
687 allocations are used to hold things such as the names of tables
688 and columns, parse tree nodes, individual query results values,
689 and B-Tree cursor objects. There are consequently
690 many calls to malloc() and free() - so many calls that malloc() and
691 free() end up using a significant fraction of the CPU time assigned
692 to SQLite.</p>
693
694 <p>SQLite <a href="releaselog/3_6_1.html">version 3.6.1</a> (2008-08-06)
695 introduced the lookaside memory allocator to
696 help reduce the memory allocation load. In the lookaside allocator,
697 each <a href="c3ref/sqlite3.html">database connection</a> preallocates a single large chunk of memory
698 (typically in the range of 60 to 120 kilobytes) and divides that chunk
699 up into small fixed-size "slots" of around 100 to 1000 byte each. This
700 becomes the lookaside memory pool. Thereafter, memory allocations
701 associated with the <a href="c3ref/sqlite3.html">database connection</a> and that are not too large
702 are satisfied using one of the lookaside pool slots rather than by calling
703 the general-purpose memory allocator. Larger allocations continue to
704 use the general-purpose memory allocator, as do allocations that occur
705 when the lookaside pool slots are all checked out.
706 But in many cases, the memory
707 allocations are small enough and there are few enough outstanding that
708 the new memory requests can be satisfied from the lookaside
709 pool.</p>
710
711 <p>Because lookaside allocations are always the same size, the allocation
712 and deallocation algorithms are very quick. There is no
713 need to coalesce adjacent free slots or search for a slot
714 of a particular size. Each <a href="c3ref/sqlite3.html">database connection</a> maintains a singly-linked
715 list of unused slots. Allocation requests simply pull the first
716 element of this list. Deallocations simply push the element back onto
717 the front of the list.
718 Furthermore, each <a href="c3ref/sqlite3.html">database connection</a> is assumed to already be
719 running in a single thread (there are mutexes already in
720 place to enforce this) so no additional mutexing is required to
721 serialize access to the lookaside slot freelist.
722 Consequently, lookaside memory
723 allocations and deallocations are very fast. In speed tests on
724 Linux and Mac OS X workstations, SQLite has shown overall performance
725 improvements as high as 10% and 15%, depending on the workload how
726 and lookaside is configured.</p>
727
728 <p>The size of the lookaside memory pool has a global default value
729 but can also be configured on a connection-by-connection basis.
730 To change the default size of the lookaside memory pool at
731 compile-time, use the
732 <a href="compile.html#default_lookaside">-DSQLITE_DEFAULT_LOOKASIDE=<i>SZ,N</i></a>
733 option.
734 To change the default size of the lookaside memory pool at
735 start-time, use the <a href="c3ref/config.html">sqlite3_config()</a> interface:</p>
736
737 <blockquote><pre>
738 <a href="c3ref/config.html">sqlite3_config</a>(<a href="c3ref/c_config_covering_index_scan.html#sqliteconfiglookaside">SQLITE_CONFIG_LOOKASIDE</a>, sz, cnt);
739 </pre></blockquote>
740
741 <p>The "sz" parameter is the size in bytes of each lookaside slot.
742 The "cnt" parameter is
743 the total number of lookaside memory slots per database connection.
744 The total amount
745 of lookaside memory allocated to each <a href="c3ref/sqlite3.html">database connection</a> is
746 sz*cnt bytes.
747 </p>
748
749 <p>The lookaside pool can be changed for an individual
750 <a href="c3ref/sqlite3.html">database connection</a> "db" using this call:</p>
751
752 <blockquote><pre>
753 <a href="c3ref/db_config.html">sqlite3_db_config</a>(db, <a href="c3ref/c_dbconfig_defensive.html#sqlitedbconfiglookaside">SQLITE_DBCONFIG_LOOKASIDE</a>, pBuf, sz, cnt);
754 </pre></blockquote>
755
756 <p>The "pBuf" parameter is a pointer to memory space that will be
757 used for the lookaside memory pool. If pBuf is NULL, then SQLite
758 will obtain its own space for the memory pool using <a href="c3ref/free.html">sqlite3_malloc()</a>.
759 The "sz" and "cnt" parameters are the size of each lookaside slot
760 and the number of slots, respectively. If pBuf is not NULL, then it
761 must point to at least sz*cnt bytes of memory.</p>
762
763 <p>The lookaside configuration can only be changed while there are
764 no outstanding lookaside allocations for the database connection.
765 Hence, the configuration should be set immediately after creating the
766 database connection using <a href="c3ref/open.html">sqlite3_open()</a> (or equivalent) and before
767 evaluating any SQL statements on the connection.</p>
768
769 <h3 id="two_size_lookaside"><span>3.3.1. </span>Two-Size Lookaside</h3>
770
771 <p>
772 Beginning with SQLite version 3.31.0 (2020-01-22),
773 lookaside supports two memory pools, each with a different size
774 slot. The small-slot pool uses 128-byte slots and the large-slot
775 pool uses whatever size is specified by <a href="c3ref/c_dbconfig_defensive.html#sqlitedbconfiglookaside">SQLITE_DBCONFIG_LOOKASIDE</a>
776 (defaulting to 1200 bytes). Splitting the pool in two like this
777 allows memory allocations to be covered by lookaside more often
778 while at the same time reducing per-database-connection heap usage
779 from 120KB down to 48KB.
780
781 </p><p>
782 Configuration continues to use the SQLITE_DBCONFIG_LOOKASIDE or
783 SQLITE_CONFIG_LOOKASIDE configuration options, as described above,
784 with parameters "sz" and "cnt". The total heap space used for
785 lookaside continues to be sz*cnt bytes. But the space is allocated
786 between the small-slot lookaside and big-slot lookaside, with
787 preference given to small-slot lookaside. The total number of
788 slots will usually exceed "cnt", since "sz" is typically much
789 larger than the small-slot size of 128 bytes.
790
791 </p><p>
792 The default lookaside configuration has changed from 100 slots
793 of 1200 bytes each (120KB) to be 40 slots of 1200 bytes each
794 (48KB). This space ends up being allocated as 93 slots of
795 128 bytes each and 30 slots of 1200 bytes each. So more lookaside
796 slots are available but much less heap space is used.
797
798 </p><p>
799 The default lookaside configuration, the size of the small-slots,
800 and the details of how heap space is allocated between small-slots
801 and big-slots, are all subject to change from one release to the
802 next.
803
804
805 <a name="memstatus"></a>
806
807 </p><h2 id="_memory_status"><span>3.4. </span> Memory status</h2>
808
809 <p>By default, SQLite keeps statistics on its memory usage. These
810 statistics are useful in helping to determine how much memory an
811 application really needs. The statistics can also be used in
812 high-reliability system to determine
813 if the memory usage is coming close to or exceeding the limits
814 of the <a href="malloc.html#nofrag">Robson proof</a> and hence that the memory allocation subsystem is
815 liable to breakdown.</p>
816
817 <p>Most memory statistics are global, and therefore the tracking of
818 statistics must be serialized with a mutex. Statistics are turned
819 on by default, but an option exists to disable them. By disabling
820 memory statistics,
821 SQLite avoids entering and leaving a mutex on each memory allocation
822 and deallocation. That savings can be noticeable on systems where
823 mutex operations are expensive. To disable memory statistics, the
824 following interface is used at start-time:</p>
825
826 <blockquote><pre>
827 <a href="c3ref/config.html">sqlite3_config</a>(<a href="c3ref/c_config_covering_index_scan.html#sqliteconfigmemstatus">SQLITE_CONFIG_MEMSTATUS</a>, onoff);
828 </pre></blockquote>
829
830 <p>The "onoff" parameter is true to enable the tracking of memory
831 statistics and false to disable statistics tracking.</p>
832
833 <p>Assuming statistics are enabled, the following routine can be used
834 to access them:</p>
835
836 <blockquote><pre>
837 <a href="c3ref/status.html">sqlite3_status</a>(<a href="c3ref/c_status_malloc_count.html#sqlitestatusmemoryused">verb</a>, &amp;current, &amp;highwater, resetflag);
838 </pre></blockquote>
839
840 <p>The "verb" argument determines what statistic is accessed.
841 There are <a href="c3ref/c_status_malloc_count.html#sqlitestatusmemoryused">various verbs</a> defined. The
842 list is expected to grow as the <a href="c3ref/status.html">sqlite3_status()</a> interface matures.
843 The current value the selected parameter is written into integer
844 "current" and the highest historical value
845 is written into integer "highwater". If resetflag is true, then
846 the high-water mark is reset down to the current value after the call
847 returns.</p>
848
849 <p>A different interface is used to find statistics associated with a
850 single <a href="c3ref/sqlite3.html">database connection</a>:</p>
851
852 <blockquote><pre>
853 <a href="c3ref/db_status.html">sqlite3_db_status</a>(db, <a href="c3ref/c_dbstatus_options.html#sqlitedbstatuslookasideused">verb</a>, &amp;current, &amp;highwater, resetflag);
854 </pre></blockquote>
855
856 <p>This interface is similar except that it takes a pointer to
857 a <a href="c3ref/sqlite3.html">database connection</a> as its first argument and returns statistics about
858 that one object rather than about the entire SQLite library.
859 The <a href="c3ref/db_status.html">sqlite3_db_status()</a> interface currently only recognizes a
860 single verb <a href="c3ref/c_dbstatus_options.html#sqlitedbstatuslookasideused">SQLITE_DBSTATUS_LOOKASIDE_USED</a>, though additional verbs
861 may be added in the future.</p>
862
863 <p>The per-connection statistics do not use global variables and hence
864 do not require mutexes to update or access. Consequently the
865 per-connection statistics continue to function even if
866 <a href="c3ref/c_config_covering_index_scan.html#sqliteconfigmemstatus">SQLITE_CONFIG_MEMSTATUS</a> is turned off.</p>
867
868 <a name="heaplimit"></a>
869 <h2 id="_setting_memory_usage_limits"><span>3.5. </span> Setting memory usage limits</h2>
870
871 <p>The <a href="c3ref/hard_heap_limit64.html">sqlite3_soft_heap_limit64()</a> interface can be used to set an
872 upper bound on the total amount of outstanding memory that the
873 general-purpose memory allocator for SQLite will allow to be outstanding
874 at one time. If attempts are made to allocate more memory than specified
875 by the soft heap limit, then SQLite will first attempt to free cache
876 memory before continuing with the allocation request. The soft heap
877 limit mechanism only works if <a href="malloc.html#memstatus">memory statistics</a> are enabled and
878 it works best
879 if the SQLite library is compiled with the <a href="compile.html#enable_memory_management">SQLITE_ENABLE_MEMORY_MANAGEMENT</a>
880 compile-time option.</p>
881
882 <p>The soft heap limit is "soft" in this sense: If SQLite is not able
883 to free up enough auxiliary memory to stay below the limit, it goes
884 ahead and allocates the extra memory and exceeds its limit. This occurs
885 under the theory that it is better to use additional memory than to fail
886 outright.</p>
887
888 <p>As of SQLite <a href="releaselog/3_6_1.html">version 3.6.1</a> (2008-08-06),
889 the soft heap limit only applies to the
890 general-purpose memory allocator. The soft heap limit does not know
891 about or interact with
892 the <a href="malloc.html#pagecache">pagecache memory allocator</a> or the <a href="malloc.html#lookaside">lookaside memory allocator</a>.
893 This deficiency will likely be addressed in a future release.</p>
894
895 <a name="nofrag"></a>
896
897 <h1 id="_mathematical_guarantees_against_memory_allocation_failures"><span>4. </span> Mathematical Guarantees Against Memory Allocation Failures</h1>
898
899 <p>The problem of dynamic memory allocation, and specifically the
900 problem of a memory allocator breakdown, has been studied by
901 J. M. Robson and the results published as:</p>
902
903 <blockquote>
904 J. M. Robson. "Bounds for Some Functions Concerning Dynamic
905 Storage Allocation". <i>Journal of the Association for
906 Computing Machinery</i>, Volume 21, Number 8, July 1974,
907 pages 491-499.
908 </blockquote>
909
910 <p>Let us use the following notation (similar but not identical to
911 Robson's notation):</p>
912
913 <blockquote>
914 <table cellpadding="10" border="0">
915 <tr><td valign="top"><b>N</b></td>
916 <td valign="top">
917 The amount of raw memory needed by the memory allocation system
918 in order to guarantee that no memory allocation will ever fail.
919 </td></tr>
920 <tr><td valign="top"><b>M</b></td>
921 <td valign="top">
922 The maximum amount of memory that the application ever has checked out
923 at any point in time.
924 </td></tr>
925 <tr><td valign="top"><b>n</b></td>
926 <td valign="top">
927 The ratio of the largest memory allocation to the smallest. We assume
928 that every memory allocation size is an integer multiple of the smallest memory
929 allocation size.
930 </td></tr>
931 </table>
932 </blockquote>
933
934 <p>Robson proves the following result:</p>
935
936 <blockquote>
937 <b>N</b> = <b>M</b>*(1 + (log<sub>2</sub> <b>n</b>)/2) - <b>n</b> + 1
938 </blockquote>
939
940 <p>Colloquially, the Robson proof shows that in order to guarantee
941 breakdown-free operation, any memory allocator must use a memory pool
942 of size <b>N</b> which exceeds the maximum amount of memory ever
943 used <b>M</b> by a multiplier that depends on <b>n</b>,
944 the ratio of the largest to the smallest allocation size. In other
945 words, unless all memory allocations are of exactly the same size
946 (<b>n</b>=1) then the system needs access to more memory than it will
947 ever use at one time. Furthermore, we see that the amount of surplus
948 memory required grows rapidly as the ratio of largest to smallest
949 allocations increases, and so there is strong incentive to keep all
950 allocations as near to the same size as possible.</p>
951
952 <p>Robson's proof is constructive.
953 He provides an algorithm for computing a sequence of allocation
954 and deallocation operations that will lead to an allocation failure due to
955 memory fragmentation if available memory is as much as one byte
956 less than <b>N</b>.
957 And, Robson shows that a power-of-two first-fit memory allocator
958 (such as implemented by <a href="malloc.html#memsys5">memsys5</a>) will never fail a memory allocation
959 provided that available memory is <b>N</b> or more bytes.</p>
960
961 <p>The values <b>M</b> and <b>n</b> are properties of the application.
962 If an application is constructed in such a way that both <b>M</b> and
963 <b>n</b> are known, or at least have known upper bounds, and if the
964 application uses
965 the <a href="malloc.html#memsys5">memsys5</a> memory allocator and is provided with <b>N</b> bytes of
966 available memory space using <a href="c3ref/c_config_covering_index_scan.html#sqliteconfigheap">SQLITE_CONFIG_HEAP</a>
967 then Robson proves that no memory allocation request will ever fail
968 within the application.
969 To put this another way, the application developer can select a value
970 for <b>N</b> that will guarantee that no call to any SQLite interface
971 will ever return <a href="rescode.html#nomem">SQLITE_NOMEM</a>. The memory pool will never become
972 so fragmented that a new memory allocation request cannot be satisfied.
973 This is an important property for
974 applications where a software fault could cause injury, physical harm, or
975 loss of irreplaceable data.</p>
976
977 <h2 id="_computing_and_controlling_parameters_m_and_n"><span>4.1. </span> Computing and controlling parameters <b>M</b> and <b>n</b></h2>
978
979 <p>The Robson proof applies separately to each of the memory allocators
980 used by SQLite:</p>
981
982 <ul>
983 <li>The general-purpose memory allocator (<a href="malloc.html#memsys5">memsys5</a>).</li>
984 <li>The <a href="malloc.html#pagecache">pagecache memory allocator</a>.</li>
985 <li>The <a href="malloc.html#lookaside">lookaside memory allocator</a>.</li>
986 </ul>
987
988 <p>For allocators other than <a href="malloc.html#memsys5">memsys5</a>,
989 all memory allocations are of the same size. Hence, <b>n</b>=1
990 and therefore <b>N</b>=<b>M</b>. In other words, the memory pool need
991 be no larger than the largest amount of memory in use at any given moment.</p>
992
993 <p>The usage of pagecache memory is somewhat harder to control in
994 SQLite version 3.6.1, though mechanisms are planned for subsequent
995 releases that will make controlling pagecache memory much easier.
996 Prior to the introduction of these new mechanisms, the only way
997 to control pagecache memory is using the <a href="pragma.html#pragma_cache_size">cache_size pragma</a>.</p>
998
999 <p>Safety-critical applications will usually want to modify the
1000 default lookaside memory configuration so that when the initial
1001 lookaside memory buffer is allocated during <a href="c3ref/open.html">sqlite3_open()</a> the
1002 resulting memory allocation is not so large as to force the <b>n</b>
1003 parameter to be too large. In order to keep <b>n</b> under control,
1004 it is best to try to keep the largest memory allocation below 2 or 4
1005 kilobytes. Hence, a reasonable default setup for the lookaside
1006 memory allocator might any one of the following:</p>
1007
1008 <blockquote><pre>
1009 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, 32, 32); /* 1K */
1010 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, 64, 32); /* 2K */
1011 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, 32, 64); /* 2K */
1012 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, 64, 64); /* 4K */
1013 </pre></blockquote>
1014
1015 <p>Another approach is to initially disable the lookaside memory
1016 allocator:</p>
1017
1018 <blockquote><pre>
1019 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, 0, 0);
1020 </pre></blockquote>
1021
1022 <p>Then let the application maintain a separate pool of larger
1023 lookaside memory buffers that it can distribute to <a href="c3ref/sqlite3.html">database connections</a>
1024 as they are created. In the common case, the application will only
1025 have a single <a href="c3ref/sqlite3.html">database connection</a> and so the lookaside memory pool
1026 can consist of a single large buffer.</p>
1027
1028 <blockquote><pre>
1029 sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE, aStatic, 256, 500);
1030 </pre></blockquote>
1031
1032 <p>The lookaside memory allocator is really intended as performance
1033 optimization, not as a method for assuring breakdown-free memory allocation,
1034 so it is not unreasonable to completely disable the lookaside memory
1035 allocator for safety-critical operations.</p>
1036
1037 <p>The general purpose memory allocator is the most difficult memory pool
1038 to manage because it supports allocations of varying sizes. Since
1039 <b>n</b> is a multiplier on <b>M</b> we want to keep <b>n</b> as small
1040 as possible. This argues for keeping the minimum allocation size for
1041 <a href="malloc.html#memsys5">memsys5</a> as large as possible. In most applications, the
1042 <a href="malloc.html#lookaside">lookaside memory allocator</a> is able to handle small allocations. So
1043 it is reasonable to set the minimum allocation size for <a href="malloc.html#memsys5">memsys5</a> to
1044 2, 4 or even 8 times the maximum size of a lookaside allocation.
1045 A minimum allocation size of 512 is a reasonable setting.</p>
1046
1047 <p>Further to keeping <b>n</b> small, one desires to keep the size of
1048 the largest memory allocations under control.
1049 Large requests to the general-purpose memory allocator
1050 might come from several sources:</p>
1051
1052 <ol>
1053 <li>SQL table rows that contain large strings or BLOBs.</li>
1054 <li>Complex SQL queries that compile down to large <a href="c3ref/stmt.html">prepared statements</a>.</li>
1055 <li>SQL parser objects used internally by <a href="c3ref/prepare.html">sqlite3_prepare_v2()</a>.</li>
1056 <li>Storage space for <a href="c3ref/sqlite3.html">database connection</a> objects.</li>
1057 <li>Page cache memory allocations that overflow into the general-purpose
1058 memory allocator.</li>
1059 <li>Lookaside buffer allocations for new <a href="c3ref/sqlite3.html">database connections</a>.</li>
1060 </ol>
1061
1062 <p>The last two allocations can be controlled and/or eliminated by
1063 configuring the <a href="malloc.html#pagecache">pagecache memory allocator</a>,
1064 and <a href="malloc.html#lookaside">lookaside memory allocator</a> appropriately, as described above.
1065 The storage space required for <a href="c3ref/sqlite3.html">database connection</a> objects depends
1066 to some extent on the length of the filename of the database file, but
1067 rarely exceeds 2KB on 32-bit systems. (More space is required on
1068 64-bit systems due to the increased size of pointers.)
1069 Each parser object uses about 1.6KB of memory. Thus, elements 3 through 6
1070 above can easily be controlled to keep the maximum memory allocation
1071 size below 2KB.</p>
1072
1073 <p>If the application is designed to manage data in small pieces,
1074 then the database should never contain any large strings or BLOBs
1075 and hence element 1 above should not be a factor. If the database
1076 does contain large strings or BLOBs, they should be read using
1077 <a href="c3ref/blob.html">incremental BLOB I/O</a> and rows that contain the
1078 large strings or BLOBs should never be update by any means other
1079 than <a href="c3ref/blob.html">incremental BLOB I/O</a>. Otherwise, the
1080 <a href="c3ref/step.html">sqlite3_step()</a> routine will need to read the entire row into
1081 contiguous memory at some point, and that will involve at least
1082 one large memory allocation.</p>
1083
1084 <p>The final source of large memory allocations is the space to hold
1085 the <a href="c3ref/stmt.html">prepared statements</a> that result from compiling complex SQL
1086 operations. Ongoing work by the SQLite developers is reducing the
1087 amount of space required here. But large and complex queries might
1088 still require <a href="c3ref/stmt.html">prepared statements</a> that are several kilobytes in
1089 size. The only workaround at the moment is for the application to
1090 break complex SQL operations up into two or more smaller and simpler
1091 operations contained in separate <a href="c3ref/stmt.html">prepared statements</a>.</p>
1092
1093 <p>All things considered, applications should normally be able to
1094 hold their maximum memory allocation size below 2K or 4K. This
1095 gives a value for log<sub>2</sub>(<b>n</b>) of 2 or 3. This will
1096 limit <b>N</b> to between 2 and 2.5 times <b>M</b>.</p>
1097
1098 <p>The maximum amount of general-purpose memory needed by the application
1099 is determined by such factors as how many simultaneous open
1100 <a href="c3ref/sqlite3.html">database connection</a> and <a href="c3ref/stmt.html">prepared statement</a> objects the application
1101 uses, and on the complexity of the <a href="c3ref/stmt.html">prepared statements</a>. For any
1102 given application, these factors are normally fixed and can be
1103 determined experimentally using <a href="c3ref/c_status_malloc_count.html#sqlitestatusmemoryused">SQLITE_STATUS_MEMORY_USED</a>.
1104 A typical application might only use about 40KB of general-purpose
1105 memory. This gives a value of <b>N</b> of around 100KB.</p>
1106
1107 <h2 id="_ductile_failure"><span>4.2. </span> Ductile failure</h2>
1108
1109 <p>If the memory allocation subsystems within SQLite are configured
1110 for breakdown-free operation but the actual memory usage exceeds
1111 design limits set by the <a href="malloc.html#nofrag">Robson proof</a>, SQLite will usually continue
1112 to operate normally.
1113 The <a href="malloc.html#pagecache">pagecache memory allocator</a>
1114 and the <a href="malloc.html#lookaside">lookaside memory allocator</a> automatically failover
1115 to the <a href="malloc.html#memsys5">memsys5</a> general-purpose memory allocator. And it is usually the
1116 case that the <a href="malloc.html#memsys5">memsys5</a> memory allocator will continue to function
1117 without fragmentation even if <b>M</b> and/or <b>n</b> exceeds the limits
1118 imposed by the <a href="malloc.html#nofrag">Robson proof</a>. The <a href="malloc.html#nofrag">Robson proof</a> shows that it is
1119 possible for a memory allocation to break down and fail in this
1120 circumstance, but such a failure requires an especially
1121 despicable sequence of allocations and deallocations - a sequence that
1122 SQLite has never been observed to follow. So in practice it is usually
1123 the case that the limits imposed by Robson can be exceeded by a
1124 considerable margin with no ill effect.</p>
1125
1126 <p>Nevertheless, application developers are admonished to monitor
1127 the state of the memory allocation subsystems and raise alarms when
1128 memory usage approaches or exceeds Robson limits. In this way,
1129 the application will provide operators with abundant warning well
1130 in advance of failure.
1131 The <a href="malloc.html#memstatus">memory statistics</a> interfaces of SQLite provide the application with
1132 all the mechanism necessary to complete the monitoring portion of
1133 this task.</p>
1134
1135 <a name="stability"></a>
1136 <h1 id="_stability_of_memory_interfaces"><span>5. </span> Stability Of Memory Interfaces</h1>
1137
1138 <p><b>Update:</b> As of SQLite version 3.7.0 (2010-07-21),
1139 all of SQLite memory allocation interfaces
1140 are considered stable and will be supported in future releases.</p>
1141 <p align="center"><small><i>This page last modified on <a href="https://sqlite.org/docsrc/honeypot" id="mtimelink" data-href="https://sqlite.org/docsrc/finfo/pages/malloc.in?m=fc088f2b1c">2022-04-18 02:55:50</a> UTC </small></i></p>
1142