powerpc: Add optimized strlen for POWER10
[glibc.git] / manual / memory.texi
blob28ec2e4e63d4187e7f095758e672c108036037da
1 @node Memory, Character Handling, Error Reporting, Top
2 @chapter Virtual Memory Allocation And Paging
3 @c %MENU% Allocating virtual memory and controlling paging
4 @cindex memory allocation
5 @cindex storage allocation
7 This chapter describes how processes manage and use memory in a system
8 that uses @theglibc{}.
10 @Theglibc{} has several functions for dynamically allocating
11 virtual memory in various ways.  They vary in generality and in
12 efficiency.  The library also provides functions for controlling paging
13 and allocation of real memory.
16 @menu
17 * Memory Concepts::             An introduction to concepts and terminology.
18 * Memory Allocation::           Allocating storage for your program data
19 * Resizing the Data Segment::   @code{brk}, @code{sbrk}
20 * Memory Protection::           Controlling access to memory regions.
21 * Locking Pages::               Preventing page faults
22 @end menu
24 Memory mapped I/O is not discussed in this chapter.  @xref{Memory-mapped I/O}.
28 @node Memory Concepts
29 @section Process Memory Concepts
31 One of the most basic resources a process has available to it is memory.
32 There are a lot of different ways systems organize memory, but in a
33 typical one, each process has one linear virtual address space, with
34 addresses running from zero to some huge maximum.  It need not be
35 contiguous; i.e., not all of these addresses actually can be used to
36 store data.
38 The virtual memory is divided into pages (4 kilobytes is typical).
39 Backing each page of virtual memory is a page of real memory (called a
40 @dfn{frame}) or some secondary storage, usually disk space.  The disk
41 space might be swap space or just some ordinary disk file.  Actually, a
42 page of all zeroes sometimes has nothing at all backing it -- there's
43 just a flag saying it is all zeroes.
44 @cindex page frame
45 @cindex frame, real memory
46 @cindex swap space
47 @cindex page, virtual memory
49 The same frame of real memory or backing store can back multiple virtual
50 pages belonging to multiple processes.  This is normally the case, for
51 example, with virtual memory occupied by @glibcadj{} code.  The same
52 real memory frame containing the @code{printf} function backs a virtual
53 memory page in each of the existing processes that has a @code{printf}
54 call in its program.
56 In order for a program to access any part of a virtual page, the page
57 must at that moment be backed by (``connected to'') a real frame.  But
58 because there is usually a lot more virtual memory than real memory, the
59 pages must move back and forth between real memory and backing store
60 regularly, coming into real memory when a process needs to access them
61 and then retreating to backing store when not needed anymore.  This
62 movement is called @dfn{paging}.
64 When a program attempts to access a page which is not at that moment
65 backed by real memory, this is known as a @dfn{page fault}.  When a page
66 fault occurs, the kernel suspends the process, places the page into a
67 real page frame (this is called ``paging in'' or ``faulting in''), then
68 resumes the process so that from the process' point of view, the page
69 was in real memory all along.  In fact, to the process, all pages always
70 seem to be in real memory.  Except for one thing: the elapsed execution
71 time of an instruction that would normally be a few nanoseconds is
72 suddenly much, much, longer (because the kernel normally has to do I/O
73 to complete the page-in).  For programs sensitive to that, the functions
74 described in @ref{Locking Pages} can control it.
75 @cindex page fault
76 @cindex paging
78 Within each virtual address space, a process has to keep track of what
79 is at which addresses, and that process is called memory allocation.
80 Allocation usually brings to mind meting out scarce resources, but in
81 the case of virtual memory, that's not a major goal, because there is
82 generally much more of it than anyone needs.  Memory allocation within a
83 process is mainly just a matter of making sure that the same byte of
84 memory isn't used to store two different things.
86 Processes allocate memory in two major ways: by exec and
87 programmatically.  Actually, forking is a third way, but it's not very
88 interesting.  @xref{Creating a Process}.
90 Exec is the operation of creating a virtual address space for a process,
91 loading its basic program into it, and executing the program.  It is
92 done by the ``exec'' family of functions (e.g. @code{execl}).  The
93 operation takes a program file (an executable), it allocates space to
94 load all the data in the executable, loads it, and transfers control to
95 it.  That data is most notably the instructions of the program (the
96 @dfn{text}), but also literals and constants in the program and even
97 some variables: C variables with the static storage class (@pxref{Memory
98 Allocation and C}).
99 @cindex executable
100 @cindex literals
101 @cindex constants
103 Once that program begins to execute, it uses programmatic allocation to
104 gain additional memory.  In a C program with @theglibc{}, there
105 are two kinds of programmatic allocation: automatic and dynamic.
106 @xref{Memory Allocation and C}.
108 Memory-mapped I/O is another form of dynamic virtual memory allocation.
109 Mapping memory to a file means declaring that the contents of certain
110 range of a process' addresses shall be identical to the contents of a
111 specified regular file.  The system makes the virtual memory initially
112 contain the contents of the file, and if you modify the memory, the
113 system writes the same modification to the file.  Note that due to the
114 magic of virtual memory and page faults, there is no reason for the
115 system to do I/O to read the file, or allocate real memory for its
116 contents, until the program accesses the virtual memory.
117 @xref{Memory-mapped I/O}.
118 @cindex memory mapped I/O
119 @cindex memory mapped file
120 @cindex files, accessing
122 Just as it programmatically allocates memory, the program can
123 programmatically deallocate (@dfn{free}) it.  You can't free the memory
124 that was allocated by exec.  When the program exits or execs, you might
125 say that all its memory gets freed, but since in both cases the address
126 space ceases to exist, the point is really moot.  @xref{Program
127 Termination}.
128 @cindex execing a program
129 @cindex freeing memory
130 @cindex exiting a program
132 A process' virtual address space is divided into segments.  A segment is
133 a contiguous range of virtual addresses.  Three important segments are:
135 @itemize @bullet
137 @item
139 The @dfn{text segment} contains a program's instructions and literals and
140 static constants.  It is allocated by exec and stays the same size for
141 the life of the virtual address space.
143 @item
144 The @dfn{data segment} is working storage for the program.  It can be
145 preallocated and preloaded by exec and the process can extend or shrink
146 it by calling functions as described in @xref{Resizing the Data
147 Segment}.  Its lower end is fixed.
149 @item
150 The @dfn{stack segment} contains a program stack.  It grows as the stack
151 grows, but doesn't shrink when the stack shrinks.
153 @end itemize
157 @node Memory Allocation
158 @section Allocating Storage For Program Data
160 This section covers how ordinary programs manage storage for their data,
161 including the famous @code{malloc} function and some fancier facilities
162 special to @theglibc{} and GNU Compiler.
164 @menu
165 * Memory Allocation and C::     How to get different kinds of allocation in C.
166 * The GNU Allocator::           An overview of the GNU @code{malloc}
167                                 implementation.
168 * Unconstrained Allocation::    The @code{malloc} facility allows fully general
169                                  dynamic allocation.
170 * Allocation Debugging::        Finding memory leaks and not freed memory.
171 * Replacing malloc::            Using your own @code{malloc}-style allocator.
172 * Obstacks::                    Obstacks are less general than malloc
173                                  but more efficient and convenient.
174 * Variable Size Automatic::     Allocation of variable-sized blocks
175                                  of automatic storage that are freed when the
176                                  calling function returns.
177 @end menu
180 @node Memory Allocation and C
181 @subsection Memory Allocation in C Programs
183 The C language supports two kinds of memory allocation through the
184 variables in C programs:
186 @itemize @bullet
187 @item
188 @dfn{Static allocation} is what happens when you declare a static or
189 global variable.  Each static or global variable defines one block of
190 space, of a fixed size.  The space is allocated once, when your program
191 is started (part of the exec operation), and is never freed.
192 @cindex static memory allocation
193 @cindex static storage class
195 @item
196 @dfn{Automatic allocation} happens when you declare an automatic
197 variable, such as a function argument or a local variable.  The space
198 for an automatic variable is allocated when the compound statement
199 containing the declaration is entered, and is freed when that
200 compound statement is exited.
201 @cindex automatic memory allocation
202 @cindex automatic storage class
204 In GNU C, the size of the automatic storage can be an expression
205 that varies.  In other C implementations, it must be a constant.
206 @end itemize
208 A third important kind of memory allocation, @dfn{dynamic allocation},
209 is not supported by C variables but is available via @glibcadj{}
210 functions.
211 @cindex dynamic memory allocation
213 @subsubsection Dynamic Memory Allocation
214 @cindex dynamic memory allocation
216 @dfn{Dynamic memory allocation} is a technique in which programs
217 determine as they are running where to store some information.  You need
218 dynamic allocation when the amount of memory you need, or how long you
219 continue to need it, depends on factors that are not known before the
220 program runs.
222 For example, you may need a block to store a line read from an input
223 file; since there is no limit to how long a line can be, you must
224 allocate the memory dynamically and make it dynamically larger as you
225 read more of the line.
227 Or, you may need a block for each record or each definition in the input
228 data; since you can't know in advance how many there will be, you must
229 allocate a new block for each record or definition as you read it.
231 When you use dynamic allocation, the allocation of a block of memory is
232 an action that the program requests explicitly.  You call a function or
233 macro when you want to allocate space, and specify the size with an
234 argument.  If you want to free the space, you do so by calling another
235 function or macro.  You can do these things whenever you want, as often
236 as you want.
238 Dynamic allocation is not supported by C variables; there is no storage
239 class ``dynamic'', and there can never be a C variable whose value is
240 stored in dynamically allocated space.  The only way to get dynamically
241 allocated memory is via a system call (which is generally via a @glibcadj{}
242 function call), and the only way to refer to dynamically
243 allocated space is through a pointer.  Because it is less convenient,
244 and because the actual process of dynamic allocation requires more
245 computation time, programmers generally use dynamic allocation only when
246 neither static nor automatic allocation will serve.
248 For example, if you want to allocate dynamically some space to hold a
249 @code{struct foobar}, you cannot declare a variable of type @code{struct
250 foobar} whose contents are the dynamically allocated space.  But you can
251 declare a variable of pointer type @code{struct foobar *} and assign it the
252 address of the space.  Then you can use the operators @samp{*} and
253 @samp{->} on this pointer variable to refer to the contents of the space:
255 @smallexample
257   struct foobar *ptr = malloc (sizeof *ptr);
258   ptr->name = x;
259   ptr->next = current_foobar;
260   current_foobar = ptr;
262 @end smallexample
264 @node The GNU Allocator
265 @subsection The GNU Allocator
266 @cindex gnu allocator
268 The @code{malloc} implementation in @theglibc{} is derived from ptmalloc
269 (pthreads malloc), which in turn is derived from dlmalloc (Doug Lea malloc).
270 This @code{malloc} may allocate memory
271 in two different ways depending on their size
272 and certain parameters that may be controlled by users. The most common way is
273 to allocate portions of memory (called chunks) from a large contiguous area of
274 memory and manage these areas to optimize their use and reduce wastage in the
275 form of unusable chunks. Traditionally the system heap was set up to be the one
276 large memory area but the @glibcadj{} @code{malloc} implementation maintains
277 multiple such areas to optimize their use in multi-threaded applications.  Each
278 such area is internally referred to as an @dfn{arena}.
280 As opposed to other versions, the @code{malloc} in @theglibc{} does not round
281 up chunk sizes to powers of two, neither for large nor for small sizes.
282 Neighboring chunks can be coalesced on a @code{free} no matter what their size
283 is.  This makes the implementation suitable for all kinds of allocation
284 patterns without generally incurring high memory waste through fragmentation.
285 The presence of multiple arenas allows multiple threads to allocate
286 memory simultaneously in separate arenas, thus improving performance.
288 The other way of memory allocation is for very large blocks, i.e. much larger
289 than a page. These requests are allocated with @code{mmap} (anonymous or via
290 @file{/dev/zero}; @pxref{Memory-mapped I/O})). This has the great advantage
291 that these chunks are returned to the system immediately when they are freed.
292 Therefore, it cannot happen that a large chunk becomes ``locked'' in between
293 smaller ones and even after calling @code{free} wastes memory.  The size
294 threshold for @code{mmap} to be used is dynamic and gets adjusted according to
295 allocation patterns of the program.  @code{mallopt} can be used to statically
296 adjust the threshold using @code{M_MMAP_THRESHOLD} and the use of @code{mmap}
297 can be disabled completely with @code{M_MMAP_MAX};
298 @pxref{Malloc Tunable Parameters}.
300 A more detailed technical description of the GNU Allocator is maintained in
301 the @glibcadj{} wiki. See
302 @uref{https://sourceware.org/glibc/wiki/MallocInternals}.
304 It is possible to use your own custom @code{malloc} instead of the
305 built-in allocator provided by @theglibc{}.  @xref{Replacing malloc}.
307 @node Unconstrained Allocation
308 @subsection Unconstrained Allocation
309 @cindex unconstrained memory allocation
310 @cindex @code{malloc} function
311 @cindex heap, dynamic allocation from
313 The most general dynamic allocation facility is @code{malloc}.  It
314 allows you to allocate blocks of memory of any size at any time, make
315 them bigger or smaller at any time, and free the blocks individually at
316 any time (or never).
318 @menu
319 * Basic Allocation::            Simple use of @code{malloc}.
320 * Malloc Examples::             Examples of @code{malloc}.  @code{xmalloc}.
321 * Freeing after Malloc::        Use @code{free} to free a block you
322                                  got with @code{malloc}.
323 * Changing Block Size::         Use @code{realloc} to make a block
324                                  bigger or smaller.
325 * Allocating Cleared Space::    Use @code{calloc} to allocate a
326                                  block and clear it.
327 * Aligned Memory Blocks::       Allocating specially aligned memory.
328 * Malloc Tunable Parameters::   Use @code{mallopt} to adjust allocation
329                                  parameters.
330 * Heap Consistency Checking::   Automatic checking for errors.
331 * Hooks for Malloc::            You can use these hooks for debugging
332                                  programs that use @code{malloc}.
333 * Statistics of Malloc::        Getting information about how much
334                                  memory your program is using.
335 * Summary of Malloc::           Summary of @code{malloc} and related functions.
336 @end menu
338 @node Basic Allocation
339 @subsubsection Basic Memory Allocation
340 @cindex allocation of memory with @code{malloc}
342 To allocate a block of memory, call @code{malloc}.  The prototype for
343 this function is in @file{stdlib.h}.
344 @pindex stdlib.h
346 @deftypefun {void *} malloc (size_t @var{size})
347 @standards{ISO, malloc.h}
348 @standards{ISO, stdlib.h}
349 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
350 @c Malloc hooks and __morecore pointers, as well as such parameters as
351 @c max_n_mmaps and max_mmapped_mem, are accessed without guards, so they
352 @c could pose a thread safety issue; in order to not declare malloc
353 @c MT-unsafe, it's modifying the hooks and parameters while multiple
354 @c threads are active that is regarded as unsafe.  An arena's next field
355 @c is initialized and never changed again, except for main_arena's,
356 @c that's protected by list_lock; next_free is only modified while
357 @c list_lock is held too.  All other data members of an arena, as well
358 @c as the metadata of the memory areas assigned to it, are only modified
359 @c while holding the arena's mutex (fastbin pointers use catomic ops
360 @c because they may be modified by free without taking the arena's
361 @c lock).  Some reassurance was needed for fastbins, for it wasn't clear
362 @c how they were initialized.  It turns out they are always
363 @c zero-initialized: main_arena's, for being static data, and other
364 @c arena's, for being just-mmapped memory.
366 @c Leaking file descriptors and memory in case of cancellation is
367 @c unavoidable without disabling cancellation, but the lock situation is
368 @c a bit more complicated: we don't have fallback arenas for malloc to
369 @c be safe to call from within signal handlers.  Error-checking mutexes
370 @c or trylock could enable us to try and use alternate arenas, even with
371 @c -DPER_THREAD (enabled by default), but supporting interruption
372 @c (cancellation or signal handling) while holding the arena list mutex
373 @c would require more work; maybe blocking signals and disabling async
374 @c cancellation while manipulating the arena lists?
376 @c __libc_malloc @asulock @aculock @acsfd @acsmem
377 @c  force_reg ok
378 @c  *malloc_hook unguarded
379 @c  arena_lock @asulock @aculock @acsfd @acsmem
380 @c   mutex_lock @asulock @aculock
381 @c   arena_get2 @asulock @aculock @acsfd @acsmem
382 @c    get_free_list @asulock @aculock
383 @c     mutex_lock (list_lock) dup @asulock @aculock
384 @c     mutex_unlock (list_lock) dup @aculock
385 @c     mutex_lock (arena lock) dup @asulock @aculock [returns locked]
386 @c    __get_nprocs ext ok @acsfd
387 @c    NARENAS_FROM_NCORES ok
388 @c    catomic_compare_and_exchange_bool_acq ok
389 @c    _int_new_arena ok @asulock @aculock @acsmem
390 @c     new_heap ok @acsmem
391 @c      mmap ok @acsmem
392 @c      munmap ok @acsmem
393 @c      mprotect ok
394 @c     chunk2mem ok
395 @c     set_head ok
396 @c     tsd_setspecific dup ok
397 @c     mutex_init ok
398 @c     mutex_lock (just-created mutex) ok, returns locked
399 @c     mutex_lock (list_lock) dup @asulock @aculock
400 @c     atomic_write_barrier ok
401 @c     mutex_unlock (list_lock) @aculock
402 @c    catomic_decrement ok
403 @c    reused_arena @asulock @aculock
404 @c      reads&writes next_to_use and iterates over arena next without guards
405 @c      those are harmless as long as we don't drop arenas from the
406 @c      NEXT list, and we never do; when a thread terminates,
407 @c      __malloc_arena_thread_freeres prepends the arena to the free_list
408 @c      NEXT_FREE list, but NEXT is never modified, so it's safe!
409 @c     mutex_trylock (arena lock) @asulock @aculock
410 @c     mutex_lock (arena lock) dup @asulock @aculock
411 @c     tsd_setspecific dup ok
412 @c  _int_malloc @acsfd @acsmem
413 @c   checked_request2size ok
414 @c    REQUEST_OUT_OF_RANGE ok
415 @c    request2size ok
416 @c   get_max_fast ok
417 @c   fastbin_index ok
418 @c   fastbin ok
419 @c   catomic_compare_and_exhange_val_acq ok
420 @c   malloc_printerr dup @mtsenv
421 @c     if we get to it, we're toast already, undefined behavior must have
422 @c     been invoked before
423 @c    libc_message @mtsenv [no leaks with cancellation disabled]
424 @c     FATAL_PREPARE ok
425 @c      pthread_setcancelstate disable ok
426 @c     libc_secure_getenv @mtsenv
427 @c      getenv @mtsenv
428 @c     open_not_cancel_2 dup @acsfd
429 @c     strchrnul ok
430 @c     WRITEV_FOR_FATAL ok
431 @c      writev ok
432 @c     mmap ok @acsmem
433 @c     munmap ok @acsmem
434 @c     BEFORE_ABORT @acsfd
435 @c      backtrace ok
436 @c      write_not_cancel dup ok
437 @c      backtrace_symbols_fd @aculock
438 @c      open_not_cancel_2 dup @acsfd
439 @c      read_not_cancel dup ok
440 @c      close_not_cancel_no_status dup @acsfd
441 @c     abort ok
442 @c    itoa_word ok
443 @c    abort ok
444 @c   check_remalloced_chunk ok/disabled
445 @c   chunk2mem dup ok
446 @c   alloc_perturb ok
447 @c   in_smallbin_range ok
448 @c   smallbin_index ok
449 @c   bin_at ok
450 @c   last ok
451 @c   malloc_consolidate ok
452 @c    get_max_fast dup ok
453 @c    clear_fastchunks ok
454 @c    unsorted_chunks dup ok
455 @c    fastbin dup ok
456 @c    atomic_exchange_acq ok
457 @c    check_inuse_chunk dup ok/disabled
458 @c    chunk_at_offset dup ok
459 @c    chunksize dup ok
460 @c    inuse_bit_at_offset dup ok
461 @c    unlink dup ok
462 @c    clear_inuse_bit_at_offset dup ok
463 @c    in_smallbin_range dup ok
464 @c    set_head dup ok
465 @c    malloc_init_state ok
466 @c     bin_at dup ok
467 @c     set_noncontiguous dup ok
468 @c     set_max_fast dup ok
469 @c     initial_top ok
470 @c      unsorted_chunks dup ok
471 @c    check_malloc_state ok/disabled
472 @c   set_inuse_bit_at_offset ok
473 @c   check_malloced_chunk ok/disabled
474 @c   largebin_index ok
475 @c   have_fastchunks ok
476 @c   unsorted_chunks ok
477 @c    bin_at ok
478 @c   chunksize ok
479 @c   chunk_at_offset ok
480 @c   set_head ok
481 @c   set_foot ok
482 @c   mark_bin ok
483 @c    idx2bit ok
484 @c   first ok
485 @c   unlink ok
486 @c    malloc_printerr dup ok
487 @c    in_smallbin_range dup ok
488 @c   idx2block ok
489 @c   idx2bit dup ok
490 @c   next_bin ok
491 @c   sysmalloc @acsfd @acsmem
492 @c    MMAP @acsmem
493 @c    set_head dup ok
494 @c    check_chunk ok/disabled
495 @c    chunk2mem dup ok
496 @c    chunksize dup ok
497 @c    chunk_at_offset dup ok
498 @c    heap_for_ptr ok
499 @c    grow_heap ok
500 @c     mprotect ok
501 @c    set_head dup ok
502 @c    new_heap @acsmem
503 @c     MMAP dup @acsmem
504 @c     munmap @acsmem
505 @c    top ok
506 @c    set_foot dup ok
507 @c    contiguous ok
508 @c    MORECORE ok
509 @c     *__morecore ok unguarded
510 @c      __default_morecore
511 @c       sbrk ok
512 @c    force_reg dup ok
513 @c    *__after_morecore_hook unguarded
514 @c    set_noncontiguous ok
515 @c    malloc_printerr dup ok
516 @c    _int_free (have_lock) @acsfd @acsmem [@asulock @aculock]
517 @c     chunksize dup ok
518 @c     mutex_unlock dup @aculock/!have_lock
519 @c     malloc_printerr dup ok
520 @c     check_inuse_chunk ok/disabled
521 @c     chunk_at_offset dup ok
522 @c     mutex_lock dup @asulock @aculock/@have_lock
523 @c     chunk2mem dup ok
524 @c     free_perturb ok
525 @c     set_fastchunks ok
526 @c      catomic_and ok
527 @c     fastbin_index dup ok
528 @c     fastbin dup ok
529 @c     catomic_compare_and_exchange_val_rel ok
530 @c     chunk_is_mmapped ok
531 @c     contiguous dup ok
532 @c     prev_inuse ok
533 @c     unlink dup ok
534 @c     inuse_bit_at_offset dup ok
535 @c     clear_inuse_bit_at_offset ok
536 @c     unsorted_chunks dup ok
537 @c     in_smallbin_range dup ok
538 @c     set_head dup ok
539 @c     set_foot dup ok
540 @c     check_free_chunk ok/disabled
541 @c     check_chunk dup ok/disabled
542 @c     have_fastchunks dup ok
543 @c     malloc_consolidate dup ok
544 @c     systrim ok
545 @c      MORECORE dup ok
546 @c      *__after_morecore_hook dup unguarded
547 @c      set_head dup ok
548 @c      check_malloc_state ok/disabled
549 @c     top dup ok
550 @c     heap_for_ptr dup ok
551 @c     heap_trim @acsfd @acsmem
552 @c      top dup ok
553 @c      chunk_at_offset dup ok
554 @c      prev_chunk ok
555 @c      chunksize dup ok
556 @c      prev_inuse dup ok
557 @c      delete_heap @acsmem
558 @c       munmap dup @acsmem
559 @c      unlink dup ok
560 @c      set_head dup ok
561 @c      shrink_heap @acsfd
562 @c       check_may_shrink_heap @acsfd
563 @c        open_not_cancel_2 @acsfd
564 @c        read_not_cancel ok
565 @c        close_not_cancel_no_status @acsfd
566 @c       MMAP dup ok
567 @c       madvise ok
568 @c     munmap_chunk @acsmem
569 @c      chunksize dup ok
570 @c      chunk_is_mmapped dup ok
571 @c      chunk2mem dup ok
572 @c      malloc_printerr dup ok
573 @c      munmap dup @acsmem
574 @c    check_malloc_state ok/disabled
575 @c  arena_get_retry @asulock @aculock @acsfd @acsmem
576 @c   mutex_unlock dup @aculock
577 @c   mutex_lock dup @asulock @aculock
578 @c   arena_get2 dup @asulock @aculock @acsfd @acsmem
579 @c  mutex_unlock @aculock
580 @c  mem2chunk ok
581 @c  chunk_is_mmapped ok
582 @c  arena_for_chunk ok
583 @c   chunk_non_main_arena ok
584 @c   heap_for_ptr ok
585 This function returns a pointer to a newly allocated block @var{size}
586 bytes long, or a null pointer (setting @code{errno})
587 if the block could not be allocated.
588 @end deftypefun
590 The contents of the block are undefined; you must initialize it yourself
591 (or use @code{calloc} instead; @pxref{Allocating Cleared Space}).
592 Normally you would convert the value to a pointer to the kind of object
593 that you want to store in the block.  Here we show an example of doing
594 so, and of initializing the space with zeros using the library function
595 @code{memset} (@pxref{Copying Strings and Arrays}):
597 @smallexample
598 struct foo *ptr = malloc (sizeof *ptr);
599 if (ptr == 0) abort ();
600 memset (ptr, 0, sizeof (struct foo));
601 @end smallexample
603 You can store the result of @code{malloc} into any pointer variable
604 without a cast, because @w{ISO C} automatically converts the type
605 @code{void *} to another type of pointer when necessary.  However, a cast
606 is necessary if the type is needed but not specified by context.
608 Remember that when allocating space for a string, the argument to
609 @code{malloc} must be one plus the length of the string.  This is
610 because a string is terminated with a null character that doesn't count
611 in the ``length'' of the string but does need space.  For example:
613 @smallexample
614 char *ptr = malloc (length + 1);
615 @end smallexample
617 @noindent
618 @xref{Representation of Strings}, for more information about this.
620 @node Malloc Examples
621 @subsubsection Examples of @code{malloc}
623 If no more space is available, @code{malloc} returns a null pointer.
624 You should check the value of @emph{every} call to @code{malloc}.  It is
625 useful to write a subroutine that calls @code{malloc} and reports an
626 error if the value is a null pointer, returning only if the value is
627 nonzero.  This function is conventionally called @code{xmalloc}.  Here
628 it is:
629 @cindex @code{xmalloc} function
631 @smallexample
632 void *
633 xmalloc (size_t size)
635   void *value = malloc (size);
636   if (value == 0)
637     fatal ("virtual memory exhausted");
638   return value;
640 @end smallexample
642 Here is a real example of using @code{malloc} (by way of @code{xmalloc}).
643 The function @code{savestring} will copy a sequence of characters into
644 a newly allocated null-terminated string:
646 @smallexample
647 @group
648 char *
649 savestring (const char *ptr, size_t len)
651   char *value = xmalloc (len + 1);
652   value[len] = '\0';
653   return memcpy (value, ptr, len);
655 @end group
656 @end smallexample
658 The block that @code{malloc} gives you is guaranteed to be aligned so
659 that it can hold any type of data.  On @gnusystems{}, the address is
660 always a multiple of eight on 32-bit systems, and a multiple of 16 on
661 64-bit systems.  Only rarely is any higher boundary (such as a page
662 boundary) necessary; for those cases, use @code{aligned_alloc} or
663 @code{posix_memalign} (@pxref{Aligned Memory Blocks}).
665 Note that the memory located after the end of the block is likely to be
666 in use for something else; perhaps a block already allocated by another
667 call to @code{malloc}.  If you attempt to treat the block as longer than
668 you asked for it to be, you are liable to destroy the data that
669 @code{malloc} uses to keep track of its blocks, or you may destroy the
670 contents of another block.  If you have already allocated a block and
671 discover you want it to be bigger, use @code{realloc} (@pxref{Changing
672 Block Size}).
674 @strong{Portability Notes:}
676 @itemize @bullet
677 @item
678 In @theglibc{}, a successful @code{malloc (0)}
679 returns a non-null pointer to a newly allocated size-zero block;
680 other implementations may return @code{NULL} instead.
681 POSIX and the ISO C standard allow both behaviors.
683 @item
684 In @theglibc{}, a failed @code{malloc} call sets @code{errno},
685 but ISO C does not require this and non-POSIX implementations
686 need not set @code{errno} when failing.
688 @item
689 In @theglibc{}, @code{malloc} always fails when @var{size} exceeds
690 @code{PTRDIFF_MAX}, to avoid problems with programs that subtract
691 pointers or use signed indexes.  Other implementations may succeed in
692 this case, leading to undefined behavior later.
693 @end itemize
695 @node Freeing after Malloc
696 @subsubsection Freeing Memory Allocated with @code{malloc}
697 @cindex freeing memory allocated with @code{malloc}
698 @cindex heap, freeing memory from
700 When you no longer need a block that you got with @code{malloc}, use the
701 function @code{free} to make the block available to be allocated again.
702 The prototype for this function is in @file{stdlib.h}.
703 @pindex stdlib.h
705 @deftypefun void free (void *@var{ptr})
706 @standards{ISO, malloc.h}
707 @standards{ISO, stdlib.h}
708 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
709 @c __libc_free @asulock @aculock @acsfd @acsmem
710 @c   releasing memory into fastbins modifies the arena without taking
711 @c   its mutex, but catomic operations ensure safety.  If two (or more)
712 @c   threads are running malloc and have their own arenas locked when
713 @c   each gets a signal whose handler free()s large (non-fastbin-able)
714 @c   blocks from each other's arena, we deadlock; this is a more general
715 @c   case of @asulock.
716 @c  *__free_hook unguarded
717 @c  mem2chunk ok
718 @c  chunk_is_mmapped ok, chunk bits not modified after allocation
719 @c  chunksize ok
720 @c  munmap_chunk dup @acsmem
721 @c  arena_for_chunk dup ok
722 @c  _int_free (!have_lock) dup @asulock @aculock @acsfd @acsmem
723 The @code{free} function deallocates the block of memory pointed at
724 by @var{ptr}.
725 @end deftypefun
727 Freeing a block alters the contents of the block.  @strong{Do not expect to
728 find any data (such as a pointer to the next block in a chain of blocks) in
729 the block after freeing it.}  Copy whatever you need out of the block before
730 freeing it!  Here is an example of the proper way to free all the blocks in
731 a chain, and the strings that they point to:
733 @smallexample
734 struct chain
735   @{
736     struct chain *next;
737     char *name;
738   @}
740 void
741 free_chain (struct chain *chain)
743   while (chain != 0)
744     @{
745       struct chain *next = chain->next;
746       free (chain->name);
747       free (chain);
748       chain = next;
749     @}
751 @end smallexample
753 Occasionally, @code{free} can actually return memory to the operating
754 system and make the process smaller.  Usually, all it can do is allow a
755 later call to @code{malloc} to reuse the space.  In the meantime, the
756 space remains in your program as part of a free-list used internally by
757 @code{malloc}.
759 The @code{free} function preserves the value of @code{errno}, so that
760 cleanup code need not worry about saving and restoring @code{errno}
761 around a call to @code{free}.  Although neither @w{ISO C} nor
762 POSIX.1-2017 requires @code{free} to preserve @code{errno}, a future
763 version of POSIX is planned to require it.
765 There is no point in freeing blocks at the end of a program, because all
766 of the program's space is given back to the system when the process
767 terminates.
769 @node Changing Block Size
770 @subsubsection Changing the Size of a Block
771 @cindex changing the size of a block (@code{malloc})
773 Often you do not know for certain how big a block you will ultimately need
774 at the time you must begin to use the block.  For example, the block might
775 be a buffer that you use to hold a line being read from a file; no matter
776 how long you make the buffer initially, you may encounter a line that is
777 longer.
779 You can make the block longer by calling @code{realloc} or
780 @code{reallocarray}.  These functions are declared in @file{stdlib.h}.
781 @pindex stdlib.h
783 @deftypefun {void *} realloc (void *@var{ptr}, size_t @var{newsize})
784 @standards{ISO, malloc.h}
785 @standards{ISO, stdlib.h}
786 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
787 @c It may call the implementations of malloc and free, so all of their
788 @c issues arise, plus the realloc hook, also accessed without guards.
790 @c __libc_realloc @asulock @aculock @acsfd @acsmem
791 @c  *__realloc_hook unguarded
792 @c  __libc_free dup @asulock @aculock @acsfd @acsmem
793 @c  __libc_malloc dup @asulock @aculock @acsfd @acsmem
794 @c  mem2chunk dup ok
795 @c  chunksize dup ok
796 @c  malloc_printerr dup ok
797 @c  checked_request2size dup ok
798 @c  chunk_is_mmapped dup ok
799 @c  mremap_chunk
800 @c   chunksize dup ok
801 @c   __mremap ok
802 @c   set_head dup ok
803 @c  MALLOC_COPY ok
804 @c   memcpy ok
805 @c  munmap_chunk dup @acsmem
806 @c  arena_for_chunk dup ok
807 @c  mutex_lock (arena mutex) dup @asulock @aculock
808 @c  _int_realloc @acsfd @acsmem
809 @c   malloc_printerr dup ok
810 @c   check_inuse_chunk dup ok/disabled
811 @c   chunk_at_offset dup ok
812 @c   chunksize dup ok
813 @c   set_head_size dup ok
814 @c   chunk_at_offset dup ok
815 @c   set_head dup ok
816 @c   chunk2mem dup ok
817 @c   inuse dup ok
818 @c   unlink dup ok
819 @c   _int_malloc dup @acsfd @acsmem
820 @c   mem2chunk dup ok
821 @c   MALLOC_COPY dup ok
822 @c   _int_free (have_lock) dup @acsfd @acsmem
823 @c   set_inuse_bit_at_offset dup ok
824 @c   set_head dup ok
825 @c  mutex_unlock (arena mutex) dup @aculock
826 @c  _int_free (!have_lock) dup @asulock @aculock @acsfd @acsmem
828 The @code{realloc} function changes the size of the block whose address is
829 @var{ptr} to be @var{newsize}.
831 Since the space after the end of the block may be in use, @code{realloc}
832 may find it necessary to copy the block to a new address where more free
833 space is available.  The value of @code{realloc} is the new address of the
834 block.  If the block needs to be moved, @code{realloc} copies the old
835 contents.
837 If you pass a null pointer for @var{ptr}, @code{realloc} behaves just
838 like @samp{malloc (@var{newsize})}.
839 Otherwise, if @var{newsize} is zero
840 @code{realloc} frees the block and returns @code{NULL}.
841 Otherwise, if @code{realloc} cannot reallocate the requested size
842 it returns @code{NULL} and sets @code{errno}; the original block
843 is left undisturbed.
844 @end deftypefun
846 @deftypefun {void *} reallocarray (void *@var{ptr}, size_t @var{nmemb}, size_t @var{size})
847 @standards{BSD, malloc.h}
848 @standards{BSD, stdlib.h}
849 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
851 The @code{reallocarray} function changes the size of the block whose address
852 is @var{ptr} to be long enough to contain a vector of @var{nmemb} elements,
853 each of size @var{size}.  It is equivalent to @samp{realloc (@var{ptr},
854 @var{nmemb} * @var{size})}, except that @code{reallocarray} fails safely if
855 the multiplication overflows, by setting @code{errno} to @code{ENOMEM},
856 returning a null pointer, and leaving the original block unchanged.
858 @code{reallocarray} should be used instead of @code{realloc} when the new size
859 of the allocated block is the result of a multiplication that might overflow.
861 @strong{Portability Note:} This function is not part of any standard.  It was
862 first introduced in OpenBSD 5.6.
863 @end deftypefun
865 Like @code{malloc}, @code{realloc} and @code{reallocarray} may return a null
866 pointer if no memory space is available to make the block bigger.  When this
867 happens, the original block is untouched; it has not been modified or
868 relocated.
870 In most cases it makes no difference what happens to the original block
871 when @code{realloc} fails, because the application program cannot continue
872 when it is out of memory, and the only thing to do is to give a fatal error
873 message.  Often it is convenient to write and use subroutines,
874 conventionally called @code{xrealloc} and @code{xreallocarray},
875 that take care of the error message
876 as @code{xmalloc} does for @code{malloc}:
877 @cindex @code{xrealloc} and @code{xreallocarray} functions
879 @smallexample
880 void *
881 xreallocarray (void *ptr, size_t nmemb, size_t size)
883   void *value = reallocarray (ptr, nmemb, size);
884   if (value == 0)
885     fatal ("Virtual memory exhausted");
886   return value;
889 void *
890 xrealloc (void *ptr, size_t size)
892   return xreallocarray (ptr, 1, size);
894 @end smallexample
896 You can also use @code{realloc} or @code{reallocarray} to make a block
897 smaller.  The reason you would do this is to avoid tying up a lot of memory
898 space when only a little is needed.
899 @comment The following is no longer true with the new malloc.
900 @comment But it seems wise to keep the warning for other implementations.
901 In several allocation implementations, making a block smaller sometimes
902 necessitates copying it, so it can fail if no other space is available.
904 @strong{Portability Notes:}
906 @itemize @bullet
907 @item
908 Portable programs should not attempt to reallocate blocks to be size zero.
909 On other implementations if @var{ptr} is non-null, @code{realloc (ptr, 0)}
910 might free the block and return a non-null pointer to a size-zero
911 object, or it might fail and return @code{NULL} without freeing the block.
912 The ISO C17 standard allows these variations.
914 @item
915 In @theglibc{}, reallocation fails if the resulting block
916 would exceed @code{PTRDIFF_MAX} in size, to avoid problems with programs
917 that subtract pointers or use signed indexes.  Other implementations may
918 succeed, leading to undefined behavior later.
920 @item
921 In @theglibc{}, if the new size is the same as the old, @code{realloc} and
922 @code{reallocarray} are guaranteed to change nothing and return the same
923 address that you gave.  However, POSIX and ISO C allow the functions
924 to relocate the object or fail in this situation.
925 @end itemize
927 @node Allocating Cleared Space
928 @subsubsection Allocating Cleared Space
930 The function @code{calloc} allocates memory and clears it to zero.  It
931 is declared in @file{stdlib.h}.
932 @pindex stdlib.h
934 @deftypefun {void *} calloc (size_t @var{count}, size_t @var{eltsize})
935 @standards{ISO, malloc.h}
936 @standards{ISO, stdlib.h}
937 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
938 @c Same caveats as malloc.
940 @c __libc_calloc @asulock @aculock @acsfd @acsmem
941 @c  *__malloc_hook dup unguarded
942 @c  memset dup ok
943 @c  arena_get @asulock @aculock @acsfd @acsmem
944 @c   arena_lock dup @asulock @aculock @acsfd @acsmem
945 @c  top dup ok
946 @c  chunksize dup ok
947 @c  heap_for_ptr dup ok
948 @c  _int_malloc dup @acsfd @acsmem
949 @c  arena_get_retry dup @asulock @aculock @acsfd @acsmem
950 @c  mutex_unlock dup @aculock
951 @c  mem2chunk dup ok
952 @c  chunk_is_mmapped dup ok
953 @c  MALLOC_ZERO ok
954 @c   memset dup ok
955 This function allocates a block long enough to contain a vector of
956 @var{count} elements, each of size @var{eltsize}.  Its contents are
957 cleared to zero before @code{calloc} returns.
958 @end deftypefun
960 You could define @code{calloc} as follows:
962 @smallexample
963 void *
964 calloc (size_t count, size_t eltsize)
966   void *value = reallocarray (0, count, eltsize);
967   if (value != 0)
968     memset (value, 0, count * eltsize);
969   return value;
971 @end smallexample
973 But in general, it is not guaranteed that @code{calloc} calls
974 @code{reallocarray} and @code{memset} internally.  For example, if the
975 @code{calloc} implementation knows for other reasons that the new
976 memory block is zero, it need not zero out the block again with
977 @code{memset}.  Also, if an application provides its own
978 @code{reallocarray} outside the C library, @code{calloc} might not use
979 that redefinition.  @xref{Replacing malloc}.
981 @node Aligned Memory Blocks
982 @subsubsection Allocating Aligned Memory Blocks
984 @cindex page boundary
985 @cindex alignment (with @code{malloc})
986 @pindex stdlib.h
987 The address of a block returned by @code{malloc} or @code{realloc} in
988 @gnusystems{} is always a multiple of eight (or sixteen on 64-bit
989 systems).  If you need a block whose address is a multiple of a higher
990 power of two than that, use @code{aligned_alloc} or @code{posix_memalign}.
991 @code{aligned_alloc} and @code{posix_memalign} are declared in
992 @file{stdlib.h}.
994 @deftypefun {void *} aligned_alloc (size_t @var{alignment}, size_t @var{size})
995 @standards{???, stdlib.h}
996 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
997 @c Alias to memalign.
998 The @code{aligned_alloc} function allocates a block of @var{size} bytes whose
999 address is a multiple of @var{alignment}.  The @var{alignment} must be a
1000 power of two and @var{size} must be a multiple of @var{alignment}.
1002 The @code{aligned_alloc} function returns a null pointer on error and sets
1003 @code{errno} to one of the following values:
1005 @table @code
1006 @item ENOMEM
1007 There was insufficient memory available to satisfy the request.
1009 @item EINVAL
1010 @var{alignment} is not a power of two.
1012 This function was introduced in @w{ISO C11} and hence may have better
1013 portability to modern non-POSIX systems than @code{posix_memalign}.
1014 @end table
1016 @end deftypefun
1018 @deftypefun {void *} memalign (size_t @var{boundary}, size_t @var{size})
1019 @standards{BSD, malloc.h}
1020 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
1021 @c Same issues as malloc.  The padding bytes are safely freed in
1022 @c _int_memalign, with the arena still locked.
1024 @c __libc_memalign @asulock @aculock @acsfd @acsmem
1025 @c  *__memalign_hook dup unguarded
1026 @c  __libc_malloc dup @asulock @aculock @acsfd @acsmem
1027 @c  arena_get dup @asulock @aculock @acsfd @acsmem
1028 @c  _int_memalign @acsfd @acsmem
1029 @c   _int_malloc dup @acsfd @acsmem
1030 @c   checked_request2size dup ok
1031 @c   mem2chunk dup ok
1032 @c   chunksize dup ok
1033 @c   chunk_is_mmapped dup ok
1034 @c   set_head dup ok
1035 @c   chunk2mem dup ok
1036 @c   set_inuse_bit_at_offset dup ok
1037 @c   set_head_size dup ok
1038 @c   _int_free (have_lock) dup @acsfd @acsmem
1039 @c   chunk_at_offset dup ok
1040 @c   check_inuse_chunk dup ok
1041 @c  arena_get_retry dup @asulock @aculock @acsfd @acsmem
1042 @c  mutex_unlock dup @aculock
1043 The @code{memalign} function allocates a block of @var{size} bytes whose
1044 address is a multiple of @var{boundary}.  The @var{boundary} must be a
1045 power of two!  The function @code{memalign} works by allocating a
1046 somewhat larger block, and then returning an address within the block
1047 that is on the specified boundary.
1049 The @code{memalign} function returns a null pointer on error and sets
1050 @code{errno} to one of the following values:
1052 @table @code
1053 @item ENOMEM
1054 There was insufficient memory available to satisfy the request.
1056 @item EINVAL
1057 @var{boundary} is not a power of two.
1059 @end table
1061 The @code{memalign} function is obsolete and @code{aligned_alloc} or
1062 @code{posix_memalign} should be used instead.
1063 @end deftypefun
1065 @deftypefun int posix_memalign (void **@var{memptr}, size_t @var{alignment}, size_t @var{size})
1066 @standards{POSIX, stdlib.h}
1067 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
1068 @c Calls memalign unless the requirements are not met (powerof2 macro is
1069 @c safe given an automatic variable as an argument) or there's a
1070 @c memalign hook (accessed unguarded, but safely).
1071 The @code{posix_memalign} function is similar to the @code{memalign}
1072 function in that it returns a buffer of @var{size} bytes aligned to a
1073 multiple of @var{alignment}.  But it adds one requirement to the
1074 parameter @var{alignment}: the value must be a power of two multiple of
1075 @code{sizeof (void *)}.
1077 If the function succeeds in allocation memory a pointer to the allocated
1078 memory is returned in @code{*@var{memptr}} and the return value is zero.
1079 Otherwise the function returns an error value indicating the problem.
1080 The possible error values returned are:
1082 @table @code
1083 @item ENOMEM
1084 There was insufficient memory available to satisfy the request.
1086 @item EINVAL
1087 @var{alignment} is not a power of two multiple of @code{sizeof (void *)}.
1089 @end table
1091 This function was introduced in POSIX 1003.1d.  Although this function is
1092 superseded by @code{aligned_alloc}, it is more portable to older POSIX
1093 systems that do not support @w{ISO C11}.
1094 @end deftypefun
1096 @deftypefun {void *} valloc (size_t @var{size})
1097 @standards{BSD, malloc.h}
1098 @standards{BSD, stdlib.h}
1099 @safety{@prelim{}@mtunsafe{@mtuinit{}}@asunsafe{@asuinit{} @asulock{}}@acunsafe{@acuinit{} @aculock{} @acsfd{} @acsmem{}}}
1100 @c __libc_valloc @mtuinit @asuinit @asulock @aculock @acsfd @acsmem
1101 @c  ptmalloc_init (once) @mtsenv @asulock @aculock @acsfd @acsmem
1102 @c   _dl_addr @asucorrupt? @aculock
1103 @c    __rtld_lock_lock_recursive (dl_load_lock) @asucorrupt? @aculock
1104 @c    _dl_find_dso_for_object ok, iterates over dl_ns and its _ns_loaded objs
1105 @c      the ok above assumes no partial updates on dl_ns and _ns_loaded
1106 @c      that could confuse a _dl_addr call in a signal handler
1107 @c     _dl_addr_inside_object ok
1108 @c    determine_info ok
1109 @c    __rtld_lock_unlock_recursive (dl_load_lock) @aculock
1110 @c   *_environ @mtsenv
1111 @c   next_env_entry ok
1112 @c   strcspn dup ok
1113 @c   __libc_mallopt dup @mtasuconst:mallopt [setting mp_]
1114 @c   *__malloc_initialize_hook unguarded, ok
1115 @c  *__memalign_hook dup ok, unguarded
1116 @c  arena_get dup @asulock @aculock @acsfd @acsmem
1117 @c  _int_valloc @acsfd @acsmem
1118 @c   malloc_consolidate dup ok
1119 @c   _int_memalign dup @acsfd @acsmem
1120 @c  arena_get_retry dup @asulock @aculock @acsfd @acsmem
1121 @c  _int_memalign dup @acsfd @acsmem
1122 @c  mutex_unlock dup @aculock
1123 Using @code{valloc} is like using @code{memalign} and passing the page size
1124 as the value of the first argument.  It is implemented like this:
1126 @smallexample
1127 void *
1128 valloc (size_t size)
1130   return memalign (getpagesize (), size);
1132 @end smallexample
1134 @ref{Query Memory Parameters} for more information about the memory
1135 subsystem.
1137 The @code{valloc} function is obsolete and @code{aligned_alloc} or
1138 @code{posix_memalign} should be used instead.
1139 @end deftypefun
1141 @node Malloc Tunable Parameters
1142 @subsubsection Malloc Tunable Parameters
1144 You can adjust some parameters for dynamic memory allocation with the
1145 @code{mallopt} function.  This function is the general SVID/XPG
1146 interface, defined in @file{malloc.h}.
1147 @pindex malloc.h
1149 @deftypefun int mallopt (int @var{param}, int @var{value})
1150 @safety{@prelim{}@mtunsafe{@mtuinit{} @mtasuconst{:mallopt}}@asunsafe{@asuinit{} @asulock{}}@acunsafe{@acuinit{} @aculock{}}}
1151 @c __libc_mallopt @mtuinit @mtasuconst:mallopt @asuinit @asulock @aculock
1152 @c  ptmalloc_init (once) dup @mtsenv @asulock @aculock @acsfd @acsmem
1153 @c  mutex_lock (main_arena->mutex) @asulock @aculock
1154 @c  malloc_consolidate dup ok
1155 @c  set_max_fast ok
1156 @c  mutex_unlock dup @aculock
1158 When calling @code{mallopt}, the @var{param} argument specifies the
1159 parameter to be set, and @var{value} the new value to be set.  Possible
1160 choices for @var{param}, as defined in @file{malloc.h}, are:
1162 @vtable @code
1163 @item M_MMAP_MAX
1164 The maximum number of chunks to allocate with @code{mmap}.  Setting this
1165 to zero disables all use of @code{mmap}.
1167 The default value of this parameter is @code{65536}.
1169 This parameter can also be set for the process at startup by setting the
1170 environment variable @env{MALLOC_MMAP_MAX_} to the desired value.
1172 @item M_MMAP_THRESHOLD
1173 All chunks larger than this value are allocated outside the normal
1174 heap, using the @code{mmap} system call.  This way it is guaranteed
1175 that the memory for these chunks can be returned to the system on
1176 @code{free}.  Note that requests smaller than this threshold might still
1177 be allocated via @code{mmap}.
1179 If this parameter is not set, the default value is set as 128 KiB and the
1180 threshold is adjusted dynamically to suit the allocation patterns of the
1181 program. If the parameter is set, the dynamic adjustment is disabled and the
1182 value is set statically to the input value.
1184 This parameter can also be set for the process at startup by setting the
1185 environment variable @env{MALLOC_MMAP_THRESHOLD_} to the desired value.
1186 @comment TODO: @item M_MXFAST
1188 @item M_PERTURB
1189 If non-zero, memory blocks are filled with values depending on some
1190 low order bits of this parameter when they are allocated (except when
1191 allocated by @code{calloc}) and freed.  This can be used to debug the
1192 use of uninitialized or freed heap memory.  Note that this option does not
1193 guarantee that the freed block will have any specific values.  It only
1194 guarantees that the content the block had before it was freed will be
1195 overwritten.
1197 The default value of this parameter is @code{0}.
1199 This parameter can also be set for the process at startup by setting the
1200 environment variable @env{MALLOC_PERTURB_} to the desired value.
1202 @item M_TOP_PAD
1203 This parameter determines the amount of extra memory to obtain from the system
1204 when an arena needs to be extended.  It also specifies the number of bytes to
1205 retain when shrinking an arena.  This provides the necessary hysteresis in heap
1206 size such that excessive amounts of system calls can be avoided.
1208 The default value of this parameter is @code{0}.
1210 This parameter can also be set for the process at startup by setting the
1211 environment variable @env{MALLOC_TOP_PAD_} to the desired value.
1213 @item M_TRIM_THRESHOLD
1214 This is the minimum size (in bytes) of the top-most, releasable chunk
1215 that will trigger a system call in order to return memory to the system.
1217 If this parameter is not set, the default value is set as 128 KiB and the
1218 threshold is adjusted dynamically to suit the allocation patterns of the
1219 program. If the parameter is set, the dynamic adjustment is disabled and the
1220 value is set statically to the provided input.
1222 This parameter can also be set for the process at startup by setting the
1223 environment variable @env{MALLOC_TRIM_THRESHOLD_} to the desired value.
1225 @item M_ARENA_TEST
1226 This parameter specifies the number of arenas that can be created before the
1227 test on the limit to the number of arenas is conducted. The value is ignored if
1228 @code{M_ARENA_MAX} is set.
1230 The default value of this parameter is 2 on 32-bit systems and 8 on 64-bit
1231 systems.
1233 This parameter can also be set for the process at startup by setting the
1234 environment variable @env{MALLOC_ARENA_TEST} to the desired value.
1236 @item M_ARENA_MAX
1237 This parameter sets the number of arenas to use regardless of the number of
1238 cores in the system.
1240 The default value of this tunable is @code{0}, meaning that the limit on the
1241 number of arenas is determined by the number of CPU cores online. For 32-bit
1242 systems the limit is twice the number of cores online and on 64-bit systems, it
1243 is eight times the number of cores online.  Note that the default value is not
1244 derived from the default value of M_ARENA_TEST and is computed independently.
1246 This parameter can also be set for the process at startup by setting the
1247 environment variable @env{MALLOC_ARENA_MAX} to the desired value.
1248 @end vtable
1250 @end deftypefun
1252 @node Heap Consistency Checking
1253 @subsubsection Heap Consistency Checking
1255 @cindex heap consistency checking
1256 @cindex consistency checking, of heap
1258 You can ask @code{malloc} to check the consistency of dynamic memory by
1259 using the @code{mcheck} function.  This function is a GNU extension,
1260 declared in @file{mcheck.h}.
1261 @pindex mcheck.h
1263 @deftypefun int mcheck (void (*@var{abortfn}) (enum mcheck_status @var{status}))
1264 @standards{GNU, mcheck.h}
1265 @safety{@prelim{}@mtunsafe{@mtasurace{:mcheck} @mtasuconst{:malloc_hooks}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
1266 @c The hooks must be set up before malloc is first used, which sort of
1267 @c implies @mtuinit/@asuinit but since the function is a no-op if malloc
1268 @c was already used, that doesn't pose any safety issues.  The actual
1269 @c problem is with the hooks, designed for single-threaded
1270 @c fully-synchronous operation: they manage an unguarded linked list of
1271 @c allocated blocks, and get temporarily overwritten before calling the
1272 @c allocation functions recursively while holding the old hooks.  There
1273 @c are no guards for thread safety, and inconsistent hooks may be found
1274 @c within signal handlers or left behind in case of cancellation.
1276 Calling @code{mcheck} tells @code{malloc} to perform occasional
1277 consistency checks.  These will catch things such as writing
1278 past the end of a block that was allocated with @code{malloc}.
1280 The @var{abortfn} argument is the function to call when an inconsistency
1281 is found.  If you supply a null pointer, then @code{mcheck} uses a
1282 default function which prints a message and calls @code{abort}
1283 (@pxref{Aborting a Program}).  The function you supply is called with
1284 one argument, which says what sort of inconsistency was detected; its
1285 type is described below.
1287 It is too late to begin allocation checking once you have allocated
1288 anything with @code{malloc}.  So @code{mcheck} does nothing in that
1289 case.  The function returns @code{-1} if you call it too late, and
1290 @code{0} otherwise (when it is successful).
1292 The easiest way to arrange to call @code{mcheck} early enough is to use
1293 the option @samp{-lmcheck} when you link your program; then you don't
1294 need to modify your program source at all.  Alternatively you might use
1295 a debugger to insert a call to @code{mcheck} whenever the program is
1296 started, for example these gdb commands will automatically call @code{mcheck}
1297 whenever the program starts:
1299 @smallexample
1300 (gdb) break main
1301 Breakpoint 1, main (argc=2, argv=0xbffff964) at whatever.c:10
1302 (gdb) command 1
1303 Type commands for when breakpoint 1 is hit, one per line.
1304 End with a line saying just "end".
1305 >call mcheck(0)
1306 >continue
1307 >end
1308 (gdb) @dots{}
1309 @end smallexample
1311 This will however only work if no initialization function of any object
1312 involved calls any of the @code{malloc} functions since @code{mcheck}
1313 must be called before the first such function.
1315 @end deftypefun
1317 @deftypefun {enum mcheck_status} mprobe (void *@var{pointer})
1318 @safety{@prelim{}@mtunsafe{@mtasurace{:mcheck} @mtasuconst{:malloc_hooks}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
1319 @c The linked list of headers may be modified concurrently by other
1320 @c threads, and it may find a partial update if called from a signal
1321 @c handler.  It's mostly read only, so cancelling it might be safe, but
1322 @c it will modify global state that, if cancellation hits at just the
1323 @c right spot, may be left behind inconsistent.  This path is only taken
1324 @c if checkhdr finds an inconsistency.  If the inconsistency could only
1325 @c occur because of earlier undefined behavior, that wouldn't be an
1326 @c additional safety issue problem, but because of the other concurrency
1327 @c issues in the mcheck hooks, the apparent inconsistency could be the
1328 @c result of mcheck's own internal data race.  So, AC-Unsafe it is.
1330 The @code{mprobe} function lets you explicitly check for inconsistencies
1331 in a particular allocated block.  You must have already called
1332 @code{mcheck} at the beginning of the program, to do its occasional
1333 checks; calling @code{mprobe} requests an additional consistency check
1334 to be done at the time of the call.
1336 The argument @var{pointer} must be a pointer returned by @code{malloc}
1337 or @code{realloc}.  @code{mprobe} returns a value that says what
1338 inconsistency, if any, was found.  The values are described below.
1339 @end deftypefun
1341 @deftp {Data Type} {enum mcheck_status}
1342 This enumerated type describes what kind of inconsistency was detected
1343 in an allocated block, if any.  Here are the possible values:
1345 @table @code
1346 @item MCHECK_DISABLED
1347 @code{mcheck} was not called before the first allocation.
1348 No consistency checking can be done.
1349 @item MCHECK_OK
1350 No inconsistency detected.
1351 @item MCHECK_HEAD
1352 The data immediately before the block was modified.
1353 This commonly happens when an array index or pointer
1354 is decremented too far.
1355 @item MCHECK_TAIL
1356 The data immediately after the block was modified.
1357 This commonly happens when an array index or pointer
1358 is incremented too far.
1359 @item MCHECK_FREE
1360 The block was already freed.
1361 @end table
1362 @end deftp
1364 Another possibility to check for and guard against bugs in the use of
1365 @code{malloc}, @code{realloc} and @code{free} is to set the environment
1366 variable @code{MALLOC_CHECK_}.  When @code{MALLOC_CHECK_} is set to a
1367 non-zero value, a special (less efficient) implementation is used which
1368 is designed to be tolerant against simple errors, such as double calls
1369 of @code{free} with the same argument, or overruns of a single byte
1370 (off-by-one bugs).  Not all such errors can be protected against,
1371 however, and memory leaks can result.
1373 Any detected heap corruption results in immediate termination of the
1374 process.
1376 There is one problem with @code{MALLOC_CHECK_}: in SUID or SGID binaries
1377 it could possibly be exploited since diverging from the normal programs
1378 behavior it now writes something to the standard error descriptor.
1379 Therefore the use of @code{MALLOC_CHECK_} is disabled by default for
1380 SUID and SGID binaries.  It can be enabled again by the system
1381 administrator by adding a file @file{/etc/suid-debug} (the content is
1382 not important it could be empty).
1384 So, what's the difference between using @code{MALLOC_CHECK_} and linking
1385 with @samp{-lmcheck}?  @code{MALLOC_CHECK_} is orthogonal with respect to
1386 @samp{-lmcheck}.  @samp{-lmcheck} has been added for backward
1387 compatibility.  Both @code{MALLOC_CHECK_} and @samp{-lmcheck} should
1388 uncover the same bugs - but using @code{MALLOC_CHECK_} you don't need to
1389 recompile your application.
1391 @node Hooks for Malloc
1392 @subsubsection Memory Allocation Hooks
1393 @cindex allocation hooks, for @code{malloc}
1395 @Theglibc{} lets you modify the behavior of @code{malloc},
1396 @code{realloc}, and @code{free} by specifying appropriate hook
1397 functions.  You can use these hooks to help you debug programs that use
1398 dynamic memory allocation, for example.
1400 The hook variables are declared in @file{malloc.h}.
1401 @pindex malloc.h
1403 @defvar __malloc_hook
1404 @standards{GNU, malloc.h}
1405 The value of this variable is a pointer to the function that
1406 @code{malloc} uses whenever it is called.  You should define this
1407 function to look like @code{malloc}; that is, like:
1409 @smallexample
1410 void *@var{function} (size_t @var{size}, const void *@var{caller})
1411 @end smallexample
1413 The value of @var{caller} is the return address found on the stack when
1414 the @code{malloc} function was called.  This value allows you to trace
1415 the memory consumption of the program.
1416 @end defvar
1418 @defvar __realloc_hook
1419 @standards{GNU, malloc.h}
1420 The value of this variable is a pointer to function that @code{realloc}
1421 uses whenever it is called.  You should define this function to look
1422 like @code{realloc}; that is, like:
1424 @smallexample
1425 void *@var{function} (void *@var{ptr}, size_t @var{size}, const void *@var{caller})
1426 @end smallexample
1428 The value of @var{caller} is the return address found on the stack when
1429 the @code{realloc} function was called.  This value allows you to trace the
1430 memory consumption of the program.
1431 @end defvar
1433 @defvar __free_hook
1434 @standards{GNU, malloc.h}
1435 The value of this variable is a pointer to function that @code{free}
1436 uses whenever it is called.  You should define this function to look
1437 like @code{free}; that is, like:
1439 @smallexample
1440 void @var{function} (void *@var{ptr}, const void *@var{caller})
1441 @end smallexample
1443 The value of @var{caller} is the return address found on the stack when
1444 the @code{free} function was called.  This value allows you to trace the
1445 memory consumption of the program.
1446 @end defvar
1448 @defvar __memalign_hook
1449 @standards{GNU, malloc.h}
1450 The value of this variable is a pointer to function that @code{aligned_alloc},
1451 @code{memalign}, @code{posix_memalign} and @code{valloc} use whenever they
1452 are called.  You should define this function to look like @code{aligned_alloc};
1453 that is, like:
1455 @smallexample
1456 void *@var{function} (size_t @var{alignment}, size_t @var{size}, const void *@var{caller})
1457 @end smallexample
1459 The value of @var{caller} is the return address found on the stack when
1460 the @code{aligned_alloc}, @code{memalign}, @code{posix_memalign} or
1461 @code{valloc} functions are called.  This value allows you to trace the
1462 memory consumption of the program.
1463 @end defvar
1465 You must make sure that the function you install as a hook for one of
1466 these functions does not call that function recursively without restoring
1467 the old value of the hook first!  Otherwise, your program will get stuck
1468 in an infinite recursion.  Before calling the function recursively, one
1469 should make sure to restore all the hooks to their previous value.  When
1470 coming back from the recursive call, all the hooks should be resaved
1471 since a hook might modify itself.
1473 An issue to look out for is the time at which the hook functions
1474 can be safely installed.  If the hook functions call the @code{malloc}-related
1475 functions recursively, it is necessary that @code{malloc} has already properly
1476 initialized itself at the time when @code{__malloc_hook} etc. is
1477 assigned to.  On the other hand, if the hook functions provide a
1478 complete @code{malloc} implementation of their own, it is vital that the hooks
1479 are assigned to @emph{before} the very first @code{malloc} call has
1480 completed, because otherwise a chunk obtained from the ordinary,
1481 un-hooked @code{malloc} may later be handed to @code{__free_hook}, for example.
1483 Here is an example showing how to use @code{__malloc_hook} and
1484 @code{__free_hook} properly.  It installs a function that prints out
1485 information every time @code{malloc} or @code{free} is called.  We just
1486 assume here that @code{realloc} and @code{memalign} are not used in our
1487 program.
1489 @smallexample
1490 /* Prototypes for __malloc_hook, __free_hook */
1491 #include <malloc.h>
1493 /* Prototypes for our hooks.  */
1494 static void my_init_hook (void);
1495 static void *my_malloc_hook (size_t, const void *);
1496 static void my_free_hook (void*, const void *);
1498 static void
1499 my_init (void)
1501   old_malloc_hook = __malloc_hook;
1502   old_free_hook = __free_hook;
1503   __malloc_hook = my_malloc_hook;
1504   __free_hook = my_free_hook;
1507 static void *
1508 my_malloc_hook (size_t size, const void *caller)
1510   void *result;
1511   /* Restore all old hooks */
1512   __malloc_hook = old_malloc_hook;
1513   __free_hook = old_free_hook;
1514   /* Call recursively */
1515   result = malloc (size);
1516   /* Save underlying hooks */
1517   old_malloc_hook = __malloc_hook;
1518   old_free_hook = __free_hook;
1519   /* @r{@code{printf} might call @code{malloc}, so protect it too.} */
1520   printf ("malloc (%u) returns %p\n", (unsigned int) size, result);
1521   /* Restore our own hooks */
1522   __malloc_hook = my_malloc_hook;
1523   __free_hook = my_free_hook;
1524   return result;
1527 static void
1528 my_free_hook (void *ptr, const void *caller)
1530   /* Restore all old hooks */
1531   __malloc_hook = old_malloc_hook;
1532   __free_hook = old_free_hook;
1533   /* Call recursively */
1534   free (ptr);
1535   /* Save underlying hooks */
1536   old_malloc_hook = __malloc_hook;
1537   old_free_hook = __free_hook;
1538   /* @r{@code{printf} might call @code{free}, so protect it too.} */
1539   printf ("freed pointer %p\n", ptr);
1540   /* Restore our own hooks */
1541   __malloc_hook = my_malloc_hook;
1542   __free_hook = my_free_hook;
1545 main ()
1547   my_init ();
1548   @dots{}
1550 @end smallexample
1552 The @code{mcheck} function (@pxref{Heap Consistency Checking}) works by
1553 installing such hooks.
1555 @c __morecore, __after_morecore_hook are undocumented
1556 @c It's not clear whether to document them.
1558 @node Statistics of Malloc
1559 @subsubsection Statistics for Memory Allocation with @code{malloc}
1561 @cindex allocation statistics
1562 You can get information about dynamic memory allocation by calling the
1563 @code{mallinfo2} function.  This function and its associated data type
1564 are declared in @file{malloc.h}; they are an extension of the standard
1565 SVID/XPG version.
1566 @pindex malloc.h
1568 @deftp {Data Type} {struct mallinfo2}
1569 @standards{GNU, malloc.h}
1570 This structure type is used to return information about the dynamic
1571 memory allocator.  It contains the following members:
1573 @table @code
1574 @item size_t arena
1575 This is the total size of memory allocated with @code{sbrk} by
1576 @code{malloc}, in bytes.
1578 @item size_t ordblks
1579 This is the number of chunks not in use.  (The memory allocator
1580 size_ternally gets chunks of memory from the operating system, and then
1581 carves them up to satisfy individual @code{malloc} requests;
1582 @pxref{The GNU Allocator}.)
1584 @item size_t smblks
1585 This field is unused.
1587 @item size_t hblks
1588 This is the total number of chunks allocated with @code{mmap}.
1590 @item size_t hblkhd
1591 This is the total size of memory allocated with @code{mmap}, in bytes.
1593 @item size_t usmblks
1594 This field is unused and always 0.
1596 @item size_t fsmblks
1597 This field is unused.
1599 @item size_t uordblks
1600 This is the total size of memory occupied by chunks handed out by
1601 @code{malloc}.
1603 @item size_t fordblks
1604 This is the total size of memory occupied by free (not in use) chunks.
1606 @item size_t keepcost
1607 This is the size of the top-most releasable chunk that normally
1608 borders the end of the heap (i.e., the high end of the virtual address
1609 space's data segment).
1611 @end table
1612 @end deftp
1614 @deftypefun {struct mallinfo2} mallinfo2 (void)
1615 @standards{SVID, malloc.h}
1616 @safety{@prelim{}@mtunsafe{@mtuinit{} @mtasuconst{:mallopt}}@asunsafe{@asuinit{} @asulock{}}@acunsafe{@acuinit{} @aculock{}}}
1617 @c Accessing mp_.n_mmaps and mp_.max_mmapped_mem, modified with atomics
1618 @c but non-atomically elsewhere, may get us inconsistent results.  We
1619 @c mark the statistics as unsafe, rather than the fast-path functions
1620 @c that collect the possibly inconsistent data.
1622 @c __libc_mallinfo2 @mtuinit @mtasuconst:mallopt @asuinit @asulock @aculock
1623 @c  ptmalloc_init (once) dup @mtsenv @asulock @aculock @acsfd @acsmem
1624 @c  mutex_lock dup @asulock @aculock
1625 @c  int_mallinfo @mtasuconst:mallopt [mp_ access on main_arena]
1626 @c   malloc_consolidate dup ok
1627 @c   check_malloc_state dup ok/disabled
1628 @c   chunksize dup ok
1629 @c   fastbin dupo ok
1630 @c   bin_at dup ok
1631 @c   last dup ok
1632 @c  mutex_unlock @aculock
1634 This function returns information about the current dynamic memory usage
1635 in a structure of type @code{struct mallinfo2}.
1636 @end deftypefun
1638 @node Summary of Malloc
1639 @subsubsection Summary of @code{malloc}-Related Functions
1641 Here is a summary of the functions that work with @code{malloc}:
1643 @table @code
1644 @item void *malloc (size_t @var{size})
1645 Allocate a block of @var{size} bytes.  @xref{Basic Allocation}.
1647 @item void free (void *@var{addr})
1648 Free a block previously allocated by @code{malloc}.  @xref{Freeing after
1649 Malloc}.
1651 @item void *realloc (void *@var{addr}, size_t @var{size})
1652 Make a block previously allocated by @code{malloc} larger or smaller,
1653 possibly by copying it to a new location.  @xref{Changing Block Size}.
1655 @item void *reallocarray (void *@var{ptr}, size_t @var{nmemb}, size_t @var{size})
1656 Change the size of a block previously allocated by @code{malloc} to
1657 @code{@var{nmemb} * @var{size}} bytes as with @code{realloc}.  @xref{Changing
1658 Block Size}.
1660 @item void *calloc (size_t @var{count}, size_t @var{eltsize})
1661 Allocate a block of @var{count} * @var{eltsize} bytes using
1662 @code{malloc}, and set its contents to zero.  @xref{Allocating Cleared
1663 Space}.
1665 @item void *valloc (size_t @var{size})
1666 Allocate a block of @var{size} bytes, starting on a page boundary.
1667 @xref{Aligned Memory Blocks}.
1669 @item void *aligned_alloc (size_t @var{size}, size_t @var{alignment})
1670 Allocate a block of @var{size} bytes, starting on an address that is a
1671 multiple of @var{alignment}.  @xref{Aligned Memory Blocks}.
1673 @item int posix_memalign (void **@var{memptr}, size_t @var{alignment}, size_t @var{size})
1674 Allocate a block of @var{size} bytes, starting on an address that is a
1675 multiple of @var{alignment}.  @xref{Aligned Memory Blocks}.
1677 @item void *memalign (size_t @var{size}, size_t @var{boundary})
1678 Allocate a block of @var{size} bytes, starting on an address that is a
1679 multiple of @var{boundary}.  @xref{Aligned Memory Blocks}.
1681 @item int mallopt (int @var{param}, int @var{value})
1682 Adjust a tunable parameter.  @xref{Malloc Tunable Parameters}.
1684 @item int mcheck (void (*@var{abortfn}) (void))
1685 Tell @code{malloc} to perform occasional consistency checks on
1686 dynamically allocated memory, and to call @var{abortfn} when an
1687 inconsistency is found.  @xref{Heap Consistency Checking}.
1689 @item void *(*__malloc_hook) (size_t @var{size}, const void *@var{caller})
1690 A pointer to a function that @code{malloc} uses whenever it is called.
1692 @item void *(*__realloc_hook) (void *@var{ptr}, size_t @var{size}, const void *@var{caller})
1693 A pointer to a function that @code{realloc} uses whenever it is called.
1695 @item void (*__free_hook) (void *@var{ptr}, const void *@var{caller})
1696 A pointer to a function that @code{free} uses whenever it is called.
1698 @item void (*__memalign_hook) (size_t @var{size}, size_t @var{alignment}, const void *@var{caller})
1699 A pointer to a function that @code{aligned_alloc}, @code{memalign},
1700 @code{posix_memalign} and @code{valloc} use whenever they are called.
1702 @item struct mallinfo2 mallinfo2 (void)
1703 Return information about the current dynamic memory usage.
1704 @xref{Statistics of Malloc}.
1705 @end table
1707 @node Allocation Debugging
1708 @subsection Allocation Debugging
1709 @cindex allocation debugging
1710 @cindex malloc debugger
1712 A complicated task when programming with languages which do not use
1713 garbage collected dynamic memory allocation is to find memory leaks.
1714 Long running programs must ensure that dynamically allocated objects are
1715 freed at the end of their lifetime.  If this does not happen the system
1716 runs out of memory, sooner or later.
1718 The @code{malloc} implementation in @theglibc{} provides some
1719 simple means to detect such leaks and obtain some information to find
1720 the location.  To do this the application must be started in a special
1721 mode which is enabled by an environment variable.  There are no speed
1722 penalties for the program if the debugging mode is not enabled.
1724 @menu
1725 * Tracing malloc::               How to install the tracing functionality.
1726 * Using the Memory Debugger::    Example programs excerpts.
1727 * Tips for the Memory Debugger:: Some more or less clever ideas.
1728 * Interpreting the traces::      What do all these lines mean?
1729 @end menu
1731 @node Tracing malloc
1732 @subsubsection How to install the tracing functionality
1734 @deftypefun void mtrace (void)
1735 @standards{GNU, mcheck.h}
1736 @safety{@prelim{}@mtunsafe{@mtsenv{} @mtasurace{:mtrace} @mtasuconst{:malloc_hooks} @mtuinit{}}@asunsafe{@asuinit{} @ascuheap{} @asucorrupt{} @asulock{}}@acunsafe{@acuinit{} @acucorrupt{} @aculock{} @acsfd{} @acsmem{}}}
1737 @c Like the mcheck hooks, these are not designed with thread safety in
1738 @c mind, because the hook pointers are temporarily modified without
1739 @c regard to other threads, signals or cancellation.
1741 @c mtrace @mtuinit @mtasurace:mtrace @mtsenv @asuinit @ascuheap @asucorrupt @acuinit @acucorrupt @aculock @acsfd @acsmem
1742 @c  __libc_secure_getenv dup @mtsenv
1743 @c  malloc dup @ascuheap @acsmem
1744 @c  fopen dup @ascuheap @asulock @aculock @acsmem @acsfd
1745 @c  fcntl dup ok
1746 @c  setvbuf dup @aculock
1747 @c  fprintf dup (on newly-created stream) @aculock
1748 @c  __cxa_atexit (once) dup @asulock @aculock @acsmem
1749 @c  free dup @ascuheap @acsmem
1750 When the @code{mtrace} function is called it looks for an environment
1751 variable named @code{MALLOC_TRACE}.  This variable is supposed to
1752 contain a valid file name.  The user must have write access.  If the
1753 file already exists it is truncated.  If the environment variable is not
1754 set or it does not name a valid file which can be opened for writing
1755 nothing is done.  The behavior of @code{malloc} etc. is not changed.
1756 For obvious reasons this also happens if the application is installed
1757 with the SUID or SGID bit set.
1759 If the named file is successfully opened, @code{mtrace} installs special
1760 handlers for the functions @code{malloc}, @code{realloc}, and
1761 @code{free} (@pxref{Hooks for Malloc}).  From then on, all uses of these
1762 functions are traced and protocolled into the file.  There is now of
1763 course a speed penalty for all calls to the traced functions so tracing
1764 should not be enabled during normal use.
1766 This function is a GNU extension and generally not available on other
1767 systems.  The prototype can be found in @file{mcheck.h}.
1768 @end deftypefun
1770 @deftypefun void muntrace (void)
1771 @standards{GNU, mcheck.h}
1772 @safety{@prelim{}@mtunsafe{@mtasurace{:mtrace} @mtasuconst{:malloc_hooks} @mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acucorrupt{} @acsmem{} @aculock{} @acsfd{}}}
1774 @c muntrace @mtasurace:mtrace @mtslocale @asucorrupt @ascuheap @acucorrupt @acsmem @aculock @acsfd
1775 @c  fprintf (fputs) dup @mtslocale @asucorrupt @ascuheap @acsmem @aculock @acucorrupt
1776 @c  fclose dup @ascuheap @asulock @aculock @acsmem @acsfd
1777 The @code{muntrace} function can be called after @code{mtrace} was used
1778 to enable tracing the @code{malloc} calls.  If no (successful) call of
1779 @code{mtrace} was made @code{muntrace} does nothing.
1781 Otherwise it deinstalls the handlers for @code{malloc}, @code{realloc},
1782 and @code{free} and then closes the protocol file.  No calls are
1783 protocolled anymore and the program runs again at full speed.
1785 This function is a GNU extension and generally not available on other
1786 systems.  The prototype can be found in @file{mcheck.h}.
1787 @end deftypefun
1789 @node Using the Memory Debugger
1790 @subsubsection Example program excerpts
1792 Even though the tracing functionality does not influence the runtime
1793 behavior of the program it is not a good idea to call @code{mtrace} in
1794 all programs.  Just imagine that you debug a program using @code{mtrace}
1795 and all other programs used in the debugging session also trace their
1796 @code{malloc} calls.  The output file would be the same for all programs
1797 and thus is unusable.  Therefore one should call @code{mtrace} only if
1798 compiled for debugging.  A program could therefore start like this:
1800 @example
1801 #include <mcheck.h>
1804 main (int argc, char *argv[])
1806 #ifdef DEBUGGING
1807   mtrace ();
1808 #endif
1809   @dots{}
1811 @end example
1813 This is all that is needed if you want to trace the calls during the
1814 whole runtime of the program.  Alternatively you can stop the tracing at
1815 any time with a call to @code{muntrace}.  It is even possible to restart
1816 the tracing again with a new call to @code{mtrace}.  But this can cause
1817 unreliable results since there may be calls of the functions which are
1818 not called.  Please note that not only the application uses the traced
1819 functions, also libraries (including the C library itself) use these
1820 functions.
1822 This last point is also why it is not a good idea to call @code{muntrace}
1823 before the program terminates.  The libraries are informed about the
1824 termination of the program only after the program returns from
1825 @code{main} or calls @code{exit} and so cannot free the memory they use
1826 before this time.
1828 So the best thing one can do is to call @code{mtrace} as the very first
1829 function in the program and never call @code{muntrace}.  So the program
1830 traces almost all uses of the @code{malloc} functions (except those
1831 calls which are executed by constructors of the program or used
1832 libraries).
1834 @node Tips for the Memory Debugger
1835 @subsubsection Some more or less clever ideas
1837 You know the situation.  The program is prepared for debugging and in
1838 all debugging sessions it runs well.  But once it is started without
1839 debugging the error shows up.  A typical example is a memory leak that
1840 becomes visible only when we turn off the debugging.  If you foresee
1841 such situations you can still win.  Simply use something equivalent to
1842 the following little program:
1844 @example
1845 #include <mcheck.h>
1846 #include <signal.h>
1848 static void
1849 enable (int sig)
1851   mtrace ();
1852   signal (SIGUSR1, enable);
1855 static void
1856 disable (int sig)
1858   muntrace ();
1859   signal (SIGUSR2, disable);
1863 main (int argc, char *argv[])
1865   @dots{}
1867   signal (SIGUSR1, enable);
1868   signal (SIGUSR2, disable);
1870   @dots{}
1872 @end example
1874 I.e., the user can start the memory debugger any time s/he wants if the
1875 program was started with @code{MALLOC_TRACE} set in the environment.
1876 The output will of course not show the allocations which happened before
1877 the first signal but if there is a memory leak this will show up
1878 nevertheless.
1880 @node Interpreting the traces
1881 @subsubsection Interpreting the traces
1883 If you take a look at the output it will look similar to this:
1885 @example
1886 = Start
1887 @ [0x8048209] - 0x8064cc8
1888 @ [0x8048209] - 0x8064ce0
1889 @ [0x8048209] - 0x8064cf8
1890 @ [0x80481eb] + 0x8064c48 0x14
1891 @ [0x80481eb] + 0x8064c60 0x14
1892 @ [0x80481eb] + 0x8064c78 0x14
1893 @ [0x80481eb] + 0x8064c90 0x14
1894 = End
1895 @end example
1897 What this all means is not really important since the trace file is not
1898 meant to be read by a human.  Therefore no attention is given to
1899 readability.  Instead there is a program which comes with @theglibc{}
1900 which interprets the traces and outputs a summary in an
1901 user-friendly way.  The program is called @code{mtrace} (it is in fact a
1902 Perl script) and it takes one or two arguments.  In any case the name of
1903 the file with the trace output must be specified.  If an optional
1904 argument precedes the name of the trace file this must be the name of
1905 the program which generated the trace.
1907 @example
1908 drepper$ mtrace tst-mtrace log
1909 No memory leaks.
1910 @end example
1912 In this case the program @code{tst-mtrace} was run and it produced a
1913 trace file @file{log}.  The message printed by @code{mtrace} shows there
1914 are no problems with the code, all allocated memory was freed
1915 afterwards.
1917 If we call @code{mtrace} on the example trace given above we would get a
1918 different outout:
1920 @example
1921 drepper$ mtrace errlog
1922 - 0x08064cc8 Free 2 was never alloc'd 0x8048209
1923 - 0x08064ce0 Free 3 was never alloc'd 0x8048209
1924 - 0x08064cf8 Free 4 was never alloc'd 0x8048209
1926 Memory not freed:
1927 -----------------
1928    Address     Size     Caller
1929 0x08064c48     0x14  at 0x80481eb
1930 0x08064c60     0x14  at 0x80481eb
1931 0x08064c78     0x14  at 0x80481eb
1932 0x08064c90     0x14  at 0x80481eb
1933 @end example
1935 We have called @code{mtrace} with only one argument and so the script
1936 has no chance to find out what is meant with the addresses given in the
1937 trace.  We can do better:
1939 @example
1940 drepper$ mtrace tst errlog
1941 - 0x08064cc8 Free 2 was never alloc'd /home/drepper/tst.c:39
1942 - 0x08064ce0 Free 3 was never alloc'd /home/drepper/tst.c:39
1943 - 0x08064cf8 Free 4 was never alloc'd /home/drepper/tst.c:39
1945 Memory not freed:
1946 -----------------
1947    Address     Size     Caller
1948 0x08064c48     0x14  at /home/drepper/tst.c:33
1949 0x08064c60     0x14  at /home/drepper/tst.c:33
1950 0x08064c78     0x14  at /home/drepper/tst.c:33
1951 0x08064c90     0x14  at /home/drepper/tst.c:33
1952 @end example
1954 Suddenly the output makes much more sense and the user can see
1955 immediately where the function calls causing the trouble can be found.
1957 Interpreting this output is not complicated.  There are at most two
1958 different situations being detected.  First, @code{free} was called for
1959 pointers which were never returned by one of the allocation functions.
1960 This is usually a very bad problem and what this looks like is shown in
1961 the first three lines of the output.  Situations like this are quite
1962 rare and if they appear they show up very drastically: the program
1963 normally crashes.
1965 The other situation which is much harder to detect are memory leaks.  As
1966 you can see in the output the @code{mtrace} function collects all this
1967 information and so can say that the program calls an allocation function
1968 from line 33 in the source file @file{/home/drepper/tst-mtrace.c} four
1969 times without freeing this memory before the program terminates.
1970 Whether this is a real problem remains to be investigated.
1972 @node Replacing malloc
1973 @subsection Replacing @code{malloc}
1975 @cindex @code{malloc} replacement
1976 @cindex @code{LD_PRELOAD} and @code{malloc}
1977 @cindex alternative @code{malloc} implementations
1978 @cindex customizing @code{malloc}
1979 @cindex interposing @code{malloc}
1980 @cindex preempting @code{malloc}
1981 @cindex replacing @code{malloc}
1982 @Theglibc{} supports replacing the built-in @code{malloc} implementation
1983 with a different allocator with the same interface.  For dynamically
1984 linked programs, this happens through ELF symbol interposition, either
1985 using shared object dependencies or @code{LD_PRELOAD}.  For static
1986 linking, the @code{malloc} replacement library must be linked in before
1987 linking against @code{libc.a} (explicitly or implicitly).
1989 @strong{Note:} Failure to provide a complete set of replacement
1990 functions (that is, all the functions used by the application,
1991 @theglibc{}, and other linked-in libraries) can lead to static linking
1992 failures, and, at run time, to heap corruption and application crashes.
1993 Replacement functions should implement the behavior documented for
1994 their counterparts in @theglibc{}; for example, the replacement
1995 @code{free} should also preserve @code{errno}.
1997 The minimum set of functions which has to be provided by a custom
1998 @code{malloc} is given in the table below.
2000 @table @code
2001 @item malloc
2002 @item free
2003 @item calloc
2004 @item realloc
2005 @end table
2007 These @code{malloc}-related functions are required for @theglibc{} to
2008 work.@footnote{Versions of @theglibc{} before 2.25 required that a
2009 custom @code{malloc} defines @code{__libc_memalign} (with the same
2010 interface as the @code{memalign} function).}
2012 The @code{malloc} implementation in @theglibc{} provides additional
2013 functionality not used by the library itself, but which is often used by
2014 other system libraries and applications.  A general-purpose replacement
2015 @code{malloc} implementation should provide definitions of these
2016 functions, too.  Their names are listed in the following table.
2018 @table @code
2019 @item aligned_alloc
2020 @item malloc_usable_size
2021 @item memalign
2022 @item posix_memalign
2023 @item pvalloc
2024 @item valloc
2025 @end table
2027 In addition, very old applications may use the obsolete @code{cfree}
2028 function.
2030 Further @code{malloc}-related functions such as @code{mallopt} or
2031 @code{mallinfo2} will not have any effect or return incorrect statistics
2032 when a replacement @code{malloc} is in use.  However, failure to replace
2033 these functions typically does not result in crashes or other incorrect
2034 application behavior, but may result in static linking failures.
2036 @node Obstacks
2037 @subsection Obstacks
2038 @cindex obstacks
2040 An @dfn{obstack} is a pool of memory containing a stack of objects.  You
2041 can create any number of separate obstacks, and then allocate objects in
2042 specified obstacks.  Within each obstack, the last object allocated must
2043 always be the first one freed, but distinct obstacks are independent of
2044 each other.
2046 Aside from this one constraint of order of freeing, obstacks are totally
2047 general: an obstack can contain any number of objects of any size.  They
2048 are implemented with macros, so allocation is usually very fast as long as
2049 the objects are usually small.  And the only space overhead per object is
2050 the padding needed to start each object on a suitable boundary.
2052 @menu
2053 * Creating Obstacks::           How to declare an obstack in your program.
2054 * Preparing for Obstacks::      Preparations needed before you can
2055                                  use obstacks.
2056 * Allocation in an Obstack::    Allocating objects in an obstack.
2057 * Freeing Obstack Objects::     Freeing objects in an obstack.
2058 * Obstack Functions::           The obstack functions are both
2059                                  functions and macros.
2060 * Growing Objects::             Making an object bigger by stages.
2061 * Extra Fast Growing::          Extra-high-efficiency (though more
2062                                  complicated) growing objects.
2063 * Status of an Obstack::        Inquiries about the status of an obstack.
2064 * Obstacks Data Alignment::     Controlling alignment of objects in obstacks.
2065 * Obstack Chunks::              How obstacks obtain and release chunks;
2066                                  efficiency considerations.
2067 * Summary of Obstacks::
2068 @end menu
2070 @node Creating Obstacks
2071 @subsubsection Creating Obstacks
2073 The utilities for manipulating obstacks are declared in the header
2074 file @file{obstack.h}.
2075 @pindex obstack.h
2077 @deftp {Data Type} {struct obstack}
2078 @standards{GNU, obstack.h}
2079 An obstack is represented by a data structure of type @code{struct
2080 obstack}.  This structure has a small fixed size; it records the status
2081 of the obstack and how to find the space in which objects are allocated.
2082 It does not contain any of the objects themselves.  You should not try
2083 to access the contents of the structure directly; use only the functions
2084 described in this chapter.
2085 @end deftp
2087 You can declare variables of type @code{struct obstack} and use them as
2088 obstacks, or you can allocate obstacks dynamically like any other kind
2089 of object.  Dynamic allocation of obstacks allows your program to have a
2090 variable number of different stacks.  (You can even allocate an
2091 obstack structure in another obstack, but this is rarely useful.)
2093 All the functions that work with obstacks require you to specify which
2094 obstack to use.  You do this with a pointer of type @code{struct obstack
2095 *}.  In the following, we often say ``an obstack'' when strictly
2096 speaking the object at hand is such a pointer.
2098 The objects in the obstack are packed into large blocks called
2099 @dfn{chunks}.  The @code{struct obstack} structure points to a chain of
2100 the chunks currently in use.
2102 The obstack library obtains a new chunk whenever you allocate an object
2103 that won't fit in the previous chunk.  Since the obstack library manages
2104 chunks automatically, you don't need to pay much attention to them, but
2105 you do need to supply a function which the obstack library should use to
2106 get a chunk.  Usually you supply a function which uses @code{malloc}
2107 directly or indirectly.  You must also supply a function to free a chunk.
2108 These matters are described in the following section.
2110 @node Preparing for Obstacks
2111 @subsubsection Preparing for Using Obstacks
2113 Each source file in which you plan to use the obstack functions
2114 must include the header file @file{obstack.h}, like this:
2116 @smallexample
2117 #include <obstack.h>
2118 @end smallexample
2120 @findex obstack_chunk_alloc
2121 @findex obstack_chunk_free
2122 Also, if the source file uses the macro @code{obstack_init}, it must
2123 declare or define two functions or macros that will be called by the
2124 obstack library.  One, @code{obstack_chunk_alloc}, is used to allocate
2125 the chunks of memory into which objects are packed.  The other,
2126 @code{obstack_chunk_free}, is used to return chunks when the objects in
2127 them are freed.  These macros should appear before any use of obstacks
2128 in the source file.
2130 Usually these are defined to use @code{malloc} via the intermediary
2131 @code{xmalloc} (@pxref{Unconstrained Allocation}).  This is done with
2132 the following pair of macro definitions:
2134 @smallexample
2135 #define obstack_chunk_alloc xmalloc
2136 #define obstack_chunk_free free
2137 @end smallexample
2139 @noindent
2140 Though the memory you get using obstacks really comes from @code{malloc},
2141 using obstacks is faster because @code{malloc} is called less often, for
2142 larger blocks of memory.  @xref{Obstack Chunks}, for full details.
2144 At run time, before the program can use a @code{struct obstack} object
2145 as an obstack, it must initialize the obstack by calling
2146 @code{obstack_init}.
2148 @deftypefun int obstack_init (struct obstack *@var{obstack-ptr})
2149 @standards{GNU, obstack.h}
2150 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{@acsmem{}}}
2151 @c obstack_init @mtsrace:obstack-ptr @acsmem
2152 @c  _obstack_begin @acsmem
2153 @c    chunkfun = obstack_chunk_alloc (suggested malloc)
2154 @c    freefun = obstack_chunk_free (suggested free)
2155 @c   *chunkfun @acsmem
2156 @c    obstack_chunk_alloc user-supplied
2157 @c   *obstack_alloc_failed_handler user-supplied
2158 @c    -> print_and_abort (default)
2160 @c print_and_abort
2161 @c  _ dup @ascuintl
2162 @c  fxprintf dup @asucorrupt @aculock @acucorrupt
2163 @c  exit @acucorrupt?
2164 Initialize obstack @var{obstack-ptr} for allocation of objects.  This
2165 function calls the obstack's @code{obstack_chunk_alloc} function.  If
2166 allocation of memory fails, the function pointed to by
2167 @code{obstack_alloc_failed_handler} is called.  The @code{obstack_init}
2168 function always returns 1 (Compatibility notice: Former versions of
2169 obstack returned 0 if allocation failed).
2170 @end deftypefun
2172 Here are two examples of how to allocate the space for an obstack and
2173 initialize it.  First, an obstack that is a static variable:
2175 @smallexample
2176 static struct obstack myobstack;
2177 @dots{}
2178 obstack_init (&myobstack);
2179 @end smallexample
2181 @noindent
2182 Second, an obstack that is itself dynamically allocated:
2184 @smallexample
2185 struct obstack *myobstack_ptr
2186   = (struct obstack *) xmalloc (sizeof (struct obstack));
2188 obstack_init (myobstack_ptr);
2189 @end smallexample
2191 @defvar obstack_alloc_failed_handler
2192 @standards{GNU, obstack.h}
2193 The value of this variable is a pointer to a function that
2194 @code{obstack} uses when @code{obstack_chunk_alloc} fails to allocate
2195 memory.  The default action is to print a message and abort.
2196 You should supply a function that either calls @code{exit}
2197 (@pxref{Program Termination}) or @code{longjmp} (@pxref{Non-Local
2198 Exits}) and doesn't return.
2200 @smallexample
2201 void my_obstack_alloc_failed (void)
2202 @dots{}
2203 obstack_alloc_failed_handler = &my_obstack_alloc_failed;
2204 @end smallexample
2206 @end defvar
2208 @node Allocation in an Obstack
2209 @subsubsection Allocation in an Obstack
2210 @cindex allocation (obstacks)
2212 The most direct way to allocate an object in an obstack is with
2213 @code{obstack_alloc}, which is invoked almost like @code{malloc}.
2215 @deftypefun {void *} obstack_alloc (struct obstack *@var{obstack-ptr}, int @var{size})
2216 @standards{GNU, obstack.h}
2217 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2218 @c obstack_alloc @mtsrace:obstack-ptr @acucorrupt @acsmem
2219 @c  obstack_blank dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2220 @c  obstack_finish dup @mtsrace:obstack-ptr @acucorrupt
2221 This allocates an uninitialized block of @var{size} bytes in an obstack
2222 and returns its address.  Here @var{obstack-ptr} specifies which obstack
2223 to allocate the block in; it is the address of the @code{struct obstack}
2224 object which represents the obstack.  Each obstack function or macro
2225 requires you to specify an @var{obstack-ptr} as the first argument.
2227 This function calls the obstack's @code{obstack_chunk_alloc} function if
2228 it needs to allocate a new chunk of memory; it calls
2229 @code{obstack_alloc_failed_handler} if allocation of memory by
2230 @code{obstack_chunk_alloc} failed.
2231 @end deftypefun
2233 For example, here is a function that allocates a copy of a string @var{str}
2234 in a specific obstack, which is in the variable @code{string_obstack}:
2236 @smallexample
2237 struct obstack string_obstack;
2239 char *
2240 copystring (char *string)
2242   size_t len = strlen (string) + 1;
2243   char *s = (char *) obstack_alloc (&string_obstack, len);
2244   memcpy (s, string, len);
2245   return s;
2247 @end smallexample
2249 To allocate a block with specified contents, use the function
2250 @code{obstack_copy}, declared like this:
2252 @deftypefun {void *} obstack_copy (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2253 @standards{GNU, obstack.h}
2254 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2255 @c obstack_copy @mtsrace:obstack-ptr @acucorrupt @acsmem
2256 @c  obstack_grow dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2257 @c  obstack_finish dup @mtsrace:obstack-ptr @acucorrupt
2258 This allocates a block and initializes it by copying @var{size}
2259 bytes of data starting at @var{address}.  It calls
2260 @code{obstack_alloc_failed_handler} if allocation of memory by
2261 @code{obstack_chunk_alloc} failed.
2262 @end deftypefun
2264 @deftypefun {void *} obstack_copy0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2265 @standards{GNU, obstack.h}
2266 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2267 @c obstack_copy0 @mtsrace:obstack-ptr @acucorrupt @acsmem
2268 @c  obstack_grow0 dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2269 @c  obstack_finish dup @mtsrace:obstack-ptr @acucorrupt
2270 Like @code{obstack_copy}, but appends an extra byte containing a null
2271 character.  This extra byte is not counted in the argument @var{size}.
2272 @end deftypefun
2274 The @code{obstack_copy0} function is convenient for copying a sequence
2275 of characters into an obstack as a null-terminated string.  Here is an
2276 example of its use:
2278 @smallexample
2279 char *
2280 obstack_savestring (char *addr, int size)
2282   return obstack_copy0 (&myobstack, addr, size);
2284 @end smallexample
2286 @noindent
2287 Contrast this with the previous example of @code{savestring} using
2288 @code{malloc} (@pxref{Basic Allocation}).
2290 @node Freeing Obstack Objects
2291 @subsubsection Freeing Objects in an Obstack
2292 @cindex freeing (obstacks)
2294 To free an object allocated in an obstack, use the function
2295 @code{obstack_free}.  Since the obstack is a stack of objects, freeing
2296 one object automatically frees all other objects allocated more recently
2297 in the same obstack.
2299 @deftypefun void obstack_free (struct obstack *@var{obstack-ptr}, void *@var{object})
2300 @standards{GNU, obstack.h}
2301 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{}}}
2302 @c obstack_free @mtsrace:obstack-ptr @acucorrupt
2303 @c  (obstack_free) @mtsrace:obstack-ptr @acucorrupt
2304 @c   *freefun dup user-supplied
2305 If @var{object} is a null pointer, everything allocated in the obstack
2306 is freed.  Otherwise, @var{object} must be the address of an object
2307 allocated in the obstack.  Then @var{object} is freed, along with
2308 everything allocated in @var{obstack-ptr} since @var{object}.
2309 @end deftypefun
2311 Note that if @var{object} is a null pointer, the result is an
2312 uninitialized obstack.  To free all memory in an obstack but leave it
2313 valid for further allocation, call @code{obstack_free} with the address
2314 of the first object allocated on the obstack:
2316 @smallexample
2317 obstack_free (obstack_ptr, first_object_allocated_ptr);
2318 @end smallexample
2320 Recall that the objects in an obstack are grouped into chunks.  When all
2321 the objects in a chunk become free, the obstack library automatically
2322 frees the chunk (@pxref{Preparing for Obstacks}).  Then other
2323 obstacks, or non-obstack allocation, can reuse the space of the chunk.
2325 @node Obstack Functions
2326 @subsubsection Obstack Functions and Macros
2327 @cindex macros
2329 The interfaces for using obstacks may be defined either as functions or
2330 as macros, depending on the compiler.  The obstack facility works with
2331 all C compilers, including both @w{ISO C} and traditional C, but there are
2332 precautions you must take if you plan to use compilers other than GNU C.
2334 If you are using an old-fashioned @w{non-ISO C} compiler, all the obstack
2335 ``functions'' are actually defined only as macros.  You can call these
2336 macros like functions, but you cannot use them in any other way (for
2337 example, you cannot take their address).
2339 Calling the macros requires a special precaution: namely, the first
2340 operand (the obstack pointer) may not contain any side effects, because
2341 it may be computed more than once.  For example, if you write this:
2343 @smallexample
2344 obstack_alloc (get_obstack (), 4);
2345 @end smallexample
2347 @noindent
2348 you will find that @code{get_obstack} may be called several times.
2349 If you use @code{*obstack_list_ptr++} as the obstack pointer argument,
2350 you will get very strange results since the incrementation may occur
2351 several times.
2353 In @w{ISO C}, each function has both a macro definition and a function
2354 definition.  The function definition is used if you take the address of the
2355 function without calling it.  An ordinary call uses the macro definition by
2356 default, but you can request the function definition instead by writing the
2357 function name in parentheses, as shown here:
2359 @smallexample
2360 char *x;
2361 void *(*funcp) ();
2362 /* @r{Use the macro}.  */
2363 x = (char *) obstack_alloc (obptr, size);
2364 /* @r{Call the function}.  */
2365 x = (char *) (obstack_alloc) (obptr, size);
2366 /* @r{Take the address of the function}.  */
2367 funcp = obstack_alloc;
2368 @end smallexample
2370 @noindent
2371 This is the same situation that exists in @w{ISO C} for the standard library
2372 functions.  @xref{Macro Definitions}.
2374 @strong{Warning:} When you do use the macros, you must observe the
2375 precaution of avoiding side effects in the first operand, even in @w{ISO C}.
2377 If you use the GNU C compiler, this precaution is not necessary, because
2378 various language extensions in GNU C permit defining the macros so as to
2379 compute each argument only once.
2381 @node Growing Objects
2382 @subsubsection Growing Objects
2383 @cindex growing objects (in obstacks)
2384 @cindex changing the size of a block (obstacks)
2386 Because memory in obstack chunks is used sequentially, it is possible to
2387 build up an object step by step, adding one or more bytes at a time to the
2388 end of the object.  With this technique, you do not need to know how much
2389 data you will put in the object until you come to the end of it.  We call
2390 this the technique of @dfn{growing objects}.  The special functions
2391 for adding data to the growing object are described in this section.
2393 You don't need to do anything special when you start to grow an object.
2394 Using one of the functions to add data to the object automatically
2395 starts it.  However, it is necessary to say explicitly when the object is
2396 finished.  This is done with the function @code{obstack_finish}.
2398 The actual address of the object thus built up is not known until the
2399 object is finished.  Until then, it always remains possible that you will
2400 add so much data that the object must be copied into a new chunk.
2402 While the obstack is in use for a growing object, you cannot use it for
2403 ordinary allocation of another object.  If you try to do so, the space
2404 already added to the growing object will become part of the other object.
2406 @deftypefun void obstack_blank (struct obstack *@var{obstack-ptr}, int @var{size})
2407 @standards{GNU, obstack.h}
2408 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2409 @c obstack_blank @mtsrace:obstack-ptr @acucorrupt @acsmem
2410 @c  _obstack_newchunk @mtsrace:obstack-ptr @acucorrupt @acsmem
2411 @c   *chunkfun dup @acsmem
2412 @c   *obstack_alloc_failed_handler dup user-supplied
2413 @c   *freefun
2414 @c  obstack_blank_fast dup @mtsrace:obstack-ptr
2415 The most basic function for adding to a growing object is
2416 @code{obstack_blank}, which adds space without initializing it.
2417 @end deftypefun
2419 @deftypefun void obstack_grow (struct obstack *@var{obstack-ptr}, void *@var{data}, int @var{size})
2420 @standards{GNU, obstack.h}
2421 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2422 @c obstack_grow @mtsrace:obstack-ptr @acucorrupt @acsmem
2423 @c  _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2424 @c  memcpy ok
2425 To add a block of initialized space, use @code{obstack_grow}, which is
2426 the growing-object analogue of @code{obstack_copy}.  It adds @var{size}
2427 bytes of data to the growing object, copying the contents from
2428 @var{data}.
2429 @end deftypefun
2431 @deftypefun void obstack_grow0 (struct obstack *@var{obstack-ptr}, void *@var{data}, int @var{size})
2432 @standards{GNU, obstack.h}
2433 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2434 @c obstack_grow0 @mtsrace:obstack-ptr @acucorrupt @acsmem
2435 @c   (no sequence point between storing NUL and incrementing next_free)
2436 @c   (multiple changes to next_free => @acucorrupt)
2437 @c  _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2438 @c  memcpy ok
2439 This is the growing-object analogue of @code{obstack_copy0}.  It adds
2440 @var{size} bytes copied from @var{data}, followed by an additional null
2441 character.
2442 @end deftypefun
2444 @deftypefun void obstack_1grow (struct obstack *@var{obstack-ptr}, char @var{c})
2445 @standards{GNU, obstack.h}
2446 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2447 @c obstack_1grow @mtsrace:obstack-ptr @acucorrupt @acsmem
2448 @c  _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2449 @c  obstack_1grow_fast dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2450 To add one character at a time, use the function @code{obstack_1grow}.
2451 It adds a single byte containing @var{c} to the growing object.
2452 @end deftypefun
2454 @deftypefun void obstack_ptr_grow (struct obstack *@var{obstack-ptr}, void *@var{data})
2455 @standards{GNU, obstack.h}
2456 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2457 @c obstack_ptr_grow @mtsrace:obstack-ptr @acucorrupt @acsmem
2458 @c  _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2459 @c  obstack_ptr_grow_fast dup @mtsrace:obstack-ptr
2460 Adding the value of a pointer one can use the function
2461 @code{obstack_ptr_grow}.  It adds @code{sizeof (void *)} bytes
2462 containing the value of @var{data}.
2463 @end deftypefun
2465 @deftypefun void obstack_int_grow (struct obstack *@var{obstack-ptr}, int @var{data})
2466 @standards{GNU, obstack.h}
2467 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2468 @c obstack_int_grow @mtsrace:obstack-ptr @acucorrupt @acsmem
2469 @c  _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2470 @c  obstack_int_grow_fast dup @mtsrace:obstack-ptr
2471 A single value of type @code{int} can be added by using the
2472 @code{obstack_int_grow} function.  It adds @code{sizeof (int)} bytes to
2473 the growing object and initializes them with the value of @var{data}.
2474 @end deftypefun
2476 @deftypefun {void *} obstack_finish (struct obstack *@var{obstack-ptr})
2477 @standards{GNU, obstack.h}
2478 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{}}}
2479 @c obstack_finish @mtsrace:obstack-ptr @acucorrupt
2480 When you are finished growing the object, use the function
2481 @code{obstack_finish} to close it off and return its final address.
2483 Once you have finished the object, the obstack is available for ordinary
2484 allocation or for growing another object.
2486 This function can return a null pointer under the same conditions as
2487 @code{obstack_alloc} (@pxref{Allocation in an Obstack}).
2488 @end deftypefun
2490 When you build an object by growing it, you will probably need to know
2491 afterward how long it became.  You need not keep track of this as you grow
2492 the object, because you can find out the length from the obstack just
2493 before finishing the object with the function @code{obstack_object_size},
2494 declared as follows:
2496 @deftypefun int obstack_object_size (struct obstack *@var{obstack-ptr})
2497 @standards{GNU, obstack.h}
2498 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
2499 This function returns the current size of the growing object, in bytes.
2500 Remember to call this function @emph{before} finishing the object.
2501 After it is finished, @code{obstack_object_size} will return zero.
2502 @end deftypefun
2504 If you have started growing an object and wish to cancel it, you should
2505 finish it and then free it, like this:
2507 @smallexample
2508 obstack_free (obstack_ptr, obstack_finish (obstack_ptr));
2509 @end smallexample
2511 @noindent
2512 This has no effect if no object was growing.
2514 @cindex shrinking objects
2515 You can use @code{obstack_blank} with a negative size argument to make
2516 the current object smaller.  Just don't try to shrink it beyond zero
2517 length---there's no telling what will happen if you do that.
2519 @node Extra Fast Growing
2520 @subsubsection Extra Fast Growing Objects
2521 @cindex efficiency and obstacks
2523 The usual functions for growing objects incur overhead for checking
2524 whether there is room for the new growth in the current chunk.  If you
2525 are frequently constructing objects in small steps of growth, this
2526 overhead can be significant.
2528 You can reduce the overhead by using special ``fast growth''
2529 functions that grow the object without checking.  In order to have a
2530 robust program, you must do the checking yourself.  If you do this checking
2531 in the simplest way each time you are about to add data to the object, you
2532 have not saved anything, because that is what the ordinary growth
2533 functions do.  But if you can arrange to check less often, or check
2534 more efficiently, then you make the program faster.
2536 The function @code{obstack_room} returns the amount of room available
2537 in the current chunk.  It is declared as follows:
2539 @deftypefun int obstack_room (struct obstack *@var{obstack-ptr})
2540 @standards{GNU, obstack.h}
2541 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
2542 This returns the number of bytes that can be added safely to the current
2543 growing object (or to an object about to be started) in obstack
2544 @var{obstack-ptr} using the fast growth functions.
2545 @end deftypefun
2547 While you know there is room, you can use these fast growth functions
2548 for adding data to a growing object:
2550 @deftypefun void obstack_1grow_fast (struct obstack *@var{obstack-ptr}, char @var{c})
2551 @standards{GNU, obstack.h}
2552 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2553 @c obstack_1grow_fast @mtsrace:obstack-ptr @acucorrupt @acsmem
2554 @c   (no sequence point between copying c and incrementing next_free)
2555 The function @code{obstack_1grow_fast} adds one byte containing the
2556 character @var{c} to the growing object in obstack @var{obstack-ptr}.
2557 @end deftypefun
2559 @deftypefun void obstack_ptr_grow_fast (struct obstack *@var{obstack-ptr}, void *@var{data})
2560 @standards{GNU, obstack.h}
2561 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
2562 @c obstack_ptr_grow_fast @mtsrace:obstack-ptr
2563 The function @code{obstack_ptr_grow_fast} adds @code{sizeof (void *)}
2564 bytes containing the value of @var{data} to the growing object in
2565 obstack @var{obstack-ptr}.
2566 @end deftypefun
2568 @deftypefun void obstack_int_grow_fast (struct obstack *@var{obstack-ptr}, int @var{data})
2569 @standards{GNU, obstack.h}
2570 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
2571 @c obstack_int_grow_fast @mtsrace:obstack-ptr
2572 The function @code{obstack_int_grow_fast} adds @code{sizeof (int)} bytes
2573 containing the value of @var{data} to the growing object in obstack
2574 @var{obstack-ptr}.
2575 @end deftypefun
2577 @deftypefun void obstack_blank_fast (struct obstack *@var{obstack-ptr}, int @var{size})
2578 @standards{GNU, obstack.h}
2579 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
2580 @c obstack_blank_fast @mtsrace:obstack-ptr
2581 The function @code{obstack_blank_fast} adds @var{size} bytes to the
2582 growing object in obstack @var{obstack-ptr} without initializing them.
2583 @end deftypefun
2585 When you check for space using @code{obstack_room} and there is not
2586 enough room for what you want to add, the fast growth functions
2587 are not safe.  In this case, simply use the corresponding ordinary
2588 growth function instead.  Very soon this will copy the object to a
2589 new chunk; then there will be lots of room available again.
2591 So, each time you use an ordinary growth function, check afterward for
2592 sufficient space using @code{obstack_room}.  Once the object is copied
2593 to a new chunk, there will be plenty of space again, so the program will
2594 start using the fast growth functions again.
2596 Here is an example:
2598 @smallexample
2599 @group
2600 void
2601 add_string (struct obstack *obstack, const char *ptr, int len)
2603   while (len > 0)
2604     @{
2605       int room = obstack_room (obstack);
2606       if (room == 0)
2607         @{
2608           /* @r{Not enough room.  Add one character slowly,}
2609              @r{which may copy to a new chunk and make room.}  */
2610           obstack_1grow (obstack, *ptr++);
2611           len--;
2612         @}
2613       else
2614         @{
2615           if (room > len)
2616             room = len;
2617           /* @r{Add fast as much as we have room for.} */
2618           len -= room;
2619           while (room-- > 0)
2620             obstack_1grow_fast (obstack, *ptr++);
2621         @}
2622     @}
2624 @end group
2625 @end smallexample
2627 @node Status of an Obstack
2628 @subsubsection Status of an Obstack
2629 @cindex obstack status
2630 @cindex status of obstack
2632 Here are functions that provide information on the current status of
2633 allocation in an obstack.  You can use them to learn about an object while
2634 still growing it.
2636 @deftypefun {void *} obstack_base (struct obstack *@var{obstack-ptr})
2637 @standards{GNU, obstack.h}
2638 @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acsafe{}}
2639 This function returns the tentative address of the beginning of the
2640 currently growing object in @var{obstack-ptr}.  If you finish the object
2641 immediately, it will have that address.  If you make it larger first, it
2642 may outgrow the current chunk---then its address will change!
2644 If no object is growing, this value says where the next object you
2645 allocate will start (once again assuming it fits in the current
2646 chunk).
2647 @end deftypefun
2649 @deftypefun {void *} obstack_next_free (struct obstack *@var{obstack-ptr})
2650 @standards{GNU, obstack.h}
2651 @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acsafe{}}
2652 This function returns the address of the first free byte in the current
2653 chunk of obstack @var{obstack-ptr}.  This is the end of the currently
2654 growing object.  If no object is growing, @code{obstack_next_free}
2655 returns the same value as @code{obstack_base}.
2656 @end deftypefun
2658 @deftypefun int obstack_object_size (struct obstack *@var{obstack-ptr})
2659 @standards{GNU, obstack.h}
2660 @c dup
2661 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
2662 This function returns the size in bytes of the currently growing object.
2663 This is equivalent to
2665 @smallexample
2666 obstack_next_free (@var{obstack-ptr}) - obstack_base (@var{obstack-ptr})
2667 @end smallexample
2668 @end deftypefun
2670 @node Obstacks Data Alignment
2671 @subsubsection Alignment of Data in Obstacks
2672 @cindex alignment (in obstacks)
2674 Each obstack has an @dfn{alignment boundary}; each object allocated in
2675 the obstack automatically starts on an address that is a multiple of the
2676 specified boundary.  By default, this boundary is aligned so that
2677 the object can hold any type of data.
2679 To access an obstack's alignment boundary, use the macro
2680 @code{obstack_alignment_mask}, whose function prototype looks like
2681 this:
2683 @deftypefn Macro int obstack_alignment_mask (struct obstack *@var{obstack-ptr})
2684 @standards{GNU, obstack.h}
2685 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2686 The value is a bit mask; a bit that is 1 indicates that the corresponding
2687 bit in the address of an object should be 0.  The mask value should be one
2688 less than a power of 2; the effect is that all object addresses are
2689 multiples of that power of 2.  The default value of the mask is a value
2690 that allows aligned objects to hold any type of data: for example, if
2691 its value is 3, any type of data can be stored at locations whose
2692 addresses are multiples of 4.  A mask value of 0 means an object can start
2693 on any multiple of 1 (that is, no alignment is required).
2695 The expansion of the macro @code{obstack_alignment_mask} is an lvalue,
2696 so you can alter the mask by assignment.  For example, this statement:
2698 @smallexample
2699 obstack_alignment_mask (obstack_ptr) = 0;
2700 @end smallexample
2702 @noindent
2703 has the effect of turning off alignment processing in the specified obstack.
2704 @end deftypefn
2706 Note that a change in alignment mask does not take effect until
2707 @emph{after} the next time an object is allocated or finished in the
2708 obstack.  If you are not growing an object, you can make the new
2709 alignment mask take effect immediately by calling @code{obstack_finish}.
2710 This will finish a zero-length object and then do proper alignment for
2711 the next object.
2713 @node Obstack Chunks
2714 @subsubsection Obstack Chunks
2715 @cindex efficiency of chunks
2716 @cindex chunks
2718 Obstacks work by allocating space for themselves in large chunks, and
2719 then parceling out space in the chunks to satisfy your requests.  Chunks
2720 are normally 4096 bytes long unless you specify a different chunk size.
2721 The chunk size includes 8 bytes of overhead that are not actually used
2722 for storing objects.  Regardless of the specified size, longer chunks
2723 will be allocated when necessary for long objects.
2725 The obstack library allocates chunks by calling the function
2726 @code{obstack_chunk_alloc}, which you must define.  When a chunk is no
2727 longer needed because you have freed all the objects in it, the obstack
2728 library frees the chunk by calling @code{obstack_chunk_free}, which you
2729 must also define.
2731 These two must be defined (as macros) or declared (as functions) in each
2732 source file that uses @code{obstack_init} (@pxref{Creating Obstacks}).
2733 Most often they are defined as macros like this:
2735 @smallexample
2736 #define obstack_chunk_alloc malloc
2737 #define obstack_chunk_free free
2738 @end smallexample
2740 Note that these are simple macros (no arguments).  Macro definitions with
2741 arguments will not work!  It is necessary that @code{obstack_chunk_alloc}
2742 or @code{obstack_chunk_free}, alone, expand into a function name if it is
2743 not itself a function name.
2745 If you allocate chunks with @code{malloc}, the chunk size should be a
2746 power of 2.  The default chunk size, 4096, was chosen because it is long
2747 enough to satisfy many typical requests on the obstack yet short enough
2748 not to waste too much memory in the portion of the last chunk not yet used.
2750 @deftypefn Macro int obstack_chunk_size (struct obstack *@var{obstack-ptr})
2751 @standards{GNU, obstack.h}
2752 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2753 This returns the chunk size of the given obstack.
2754 @end deftypefn
2756 Since this macro expands to an lvalue, you can specify a new chunk size by
2757 assigning it a new value.  Doing so does not affect the chunks already
2758 allocated, but will change the size of chunks allocated for that particular
2759 obstack in the future.  It is unlikely to be useful to make the chunk size
2760 smaller, but making it larger might improve efficiency if you are
2761 allocating many objects whose size is comparable to the chunk size.  Here
2762 is how to do so cleanly:
2764 @smallexample
2765 if (obstack_chunk_size (obstack_ptr) < @var{new-chunk-size})
2766   obstack_chunk_size (obstack_ptr) = @var{new-chunk-size};
2767 @end smallexample
2769 @node Summary of Obstacks
2770 @subsubsection Summary of Obstack Functions
2772 Here is a summary of all the functions associated with obstacks.  Each
2773 takes the address of an obstack (@code{struct obstack *}) as its first
2774 argument.
2776 @table @code
2777 @item void obstack_init (struct obstack *@var{obstack-ptr})
2778 Initialize use of an obstack.  @xref{Creating Obstacks}.
2780 @item void *obstack_alloc (struct obstack *@var{obstack-ptr}, int @var{size})
2781 Allocate an object of @var{size} uninitialized bytes.
2782 @xref{Allocation in an Obstack}.
2784 @item void *obstack_copy (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2785 Allocate an object of @var{size} bytes, with contents copied from
2786 @var{address}.  @xref{Allocation in an Obstack}.
2788 @item void *obstack_copy0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2789 Allocate an object of @var{size}+1 bytes, with @var{size} of them copied
2790 from @var{address}, followed by a null character at the end.
2791 @xref{Allocation in an Obstack}.
2793 @item void obstack_free (struct obstack *@var{obstack-ptr}, void *@var{object})
2794 Free @var{object} (and everything allocated in the specified obstack
2795 more recently than @var{object}).  @xref{Freeing Obstack Objects}.
2797 @item void obstack_blank (struct obstack *@var{obstack-ptr}, int @var{size})
2798 Add @var{size} uninitialized bytes to a growing object.
2799 @xref{Growing Objects}.
2801 @item void obstack_grow (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2802 Add @var{size} bytes, copied from @var{address}, to a growing object.
2803 @xref{Growing Objects}.
2805 @item void obstack_grow0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2806 Add @var{size} bytes, copied from @var{address}, to a growing object,
2807 and then add another byte containing a null character.  @xref{Growing
2808 Objects}.
2810 @item void obstack_1grow (struct obstack *@var{obstack-ptr}, char @var{data-char})
2811 Add one byte containing @var{data-char} to a growing object.
2812 @xref{Growing Objects}.
2814 @item void *obstack_finish (struct obstack *@var{obstack-ptr})
2815 Finalize the object that is growing and return its permanent address.
2816 @xref{Growing Objects}.
2818 @item int obstack_object_size (struct obstack *@var{obstack-ptr})
2819 Get the current size of the currently growing object.  @xref{Growing
2820 Objects}.
2822 @item void obstack_blank_fast (struct obstack *@var{obstack-ptr}, int @var{size})
2823 Add @var{size} uninitialized bytes to a growing object without checking
2824 that there is enough room.  @xref{Extra Fast Growing}.
2826 @item void obstack_1grow_fast (struct obstack *@var{obstack-ptr}, char @var{data-char})
2827 Add one byte containing @var{data-char} to a growing object without
2828 checking that there is enough room.  @xref{Extra Fast Growing}.
2830 @item int obstack_room (struct obstack *@var{obstack-ptr})
2831 Get the amount of room now available for growing the current object.
2832 @xref{Extra Fast Growing}.
2834 @item int obstack_alignment_mask (struct obstack *@var{obstack-ptr})
2835 The mask used for aligning the beginning of an object.  This is an
2836 lvalue.  @xref{Obstacks Data Alignment}.
2838 @item int obstack_chunk_size (struct obstack *@var{obstack-ptr})
2839 The size for allocating chunks.  This is an lvalue.  @xref{Obstack Chunks}.
2841 @item void *obstack_base (struct obstack *@var{obstack-ptr})
2842 Tentative starting address of the currently growing object.
2843 @xref{Status of an Obstack}.
2845 @item void *obstack_next_free (struct obstack *@var{obstack-ptr})
2846 Address just after the end of the currently growing object.
2847 @xref{Status of an Obstack}.
2848 @end table
2850 @node Variable Size Automatic
2851 @subsection Automatic Storage with Variable Size
2852 @cindex automatic freeing
2853 @cindex @code{alloca} function
2854 @cindex automatic storage with variable size
2856 The function @code{alloca} supports a kind of half-dynamic allocation in
2857 which blocks are allocated dynamically but freed automatically.
2859 Allocating a block with @code{alloca} is an explicit action; you can
2860 allocate as many blocks as you wish, and compute the size at run time.  But
2861 all the blocks are freed when you exit the function that @code{alloca} was
2862 called from, just as if they were automatic variables declared in that
2863 function.  There is no way to free the space explicitly.
2865 The prototype for @code{alloca} is in @file{stdlib.h}.  This function is
2866 a BSD extension.
2867 @pindex stdlib.h
2869 @deftypefun {void *} alloca (size_t @var{size})
2870 @standards{GNU, stdlib.h}
2871 @standards{BSD, stdlib.h}
2872 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2873 The return value of @code{alloca} is the address of a block of @var{size}
2874 bytes of memory, allocated in the stack frame of the calling function.
2875 @end deftypefun
2877 Do not use @code{alloca} inside the arguments of a function call---you
2878 will get unpredictable results, because the stack space for the
2879 @code{alloca} would appear on the stack in the middle of the space for
2880 the function arguments.  An example of what to avoid is @code{foo (x,
2881 alloca (4), y)}.
2882 @c This might get fixed in future versions of GCC, but that won't make
2883 @c it safe with compilers generally.
2885 @menu
2886 * Alloca Example::              Example of using @code{alloca}.
2887 * Advantages of Alloca::        Reasons to use @code{alloca}.
2888 * Disadvantages of Alloca::     Reasons to avoid @code{alloca}.
2889 * GNU C Variable-Size Arrays::  Only in GNU C, here is an alternative
2890                                  method of allocating dynamically and
2891                                  freeing automatically.
2892 @end menu
2894 @node Alloca Example
2895 @subsubsection @code{alloca} Example
2897 As an example of the use of @code{alloca}, here is a function that opens
2898 a file name made from concatenating two argument strings, and returns a
2899 file descriptor or minus one signifying failure:
2901 @smallexample
2903 open2 (char *str1, char *str2, int flags, int mode)
2905   char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
2906   stpcpy (stpcpy (name, str1), str2);
2907   return open (name, flags, mode);
2909 @end smallexample
2911 @noindent
2912 Here is how you would get the same results with @code{malloc} and
2913 @code{free}:
2915 @smallexample
2917 open2 (char *str1, char *str2, int flags, int mode)
2919   char *name = malloc (strlen (str1) + strlen (str2) + 1);
2920   int desc;
2921   if (name == 0)
2922     fatal ("virtual memory exceeded");
2923   stpcpy (stpcpy (name, str1), str2);
2924   desc = open (name, flags, mode);
2925   free (name);
2926   return desc;
2928 @end smallexample
2930 As you can see, it is simpler with @code{alloca}.  But @code{alloca} has
2931 other, more important advantages, and some disadvantages.
2933 @node Advantages of Alloca
2934 @subsubsection Advantages of @code{alloca}
2936 Here are the reasons why @code{alloca} may be preferable to @code{malloc}:
2938 @itemize @bullet
2939 @item
2940 Using @code{alloca} wastes very little space and is very fast.  (It is
2941 open-coded by the GNU C compiler.)
2943 @item
2944 Since @code{alloca} does not have separate pools for different sizes of
2945 blocks, space used for any size block can be reused for any other size.
2946 @code{alloca} does not cause memory fragmentation.
2948 @item
2949 @cindex longjmp
2950 Nonlocal exits done with @code{longjmp} (@pxref{Non-Local Exits})
2951 automatically free the space allocated with @code{alloca} when they exit
2952 through the function that called @code{alloca}.  This is the most
2953 important reason to use @code{alloca}.
2955 To illustrate this, suppose you have a function
2956 @code{open_or_report_error} which returns a descriptor, like
2957 @code{open}, if it succeeds, but does not return to its caller if it
2958 fails.  If the file cannot be opened, it prints an error message and
2959 jumps out to the command level of your program using @code{longjmp}.
2960 Let's change @code{open2} (@pxref{Alloca Example}) to use this
2961 subroutine:@refill
2963 @smallexample
2965 open2 (char *str1, char *str2, int flags, int mode)
2967   char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
2968   stpcpy (stpcpy (name, str1), str2);
2969   return open_or_report_error (name, flags, mode);
2971 @end smallexample
2973 @noindent
2974 Because of the way @code{alloca} works, the memory it allocates is
2975 freed even when an error occurs, with no special effort required.
2977 By contrast, the previous definition of @code{open2} (which uses
2978 @code{malloc} and @code{free}) would develop a memory leak if it were
2979 changed in this way.  Even if you are willing to make more changes to
2980 fix it, there is no easy way to do so.
2981 @end itemize
2983 @node Disadvantages of Alloca
2984 @subsubsection Disadvantages of @code{alloca}
2986 @cindex @code{alloca} disadvantages
2987 @cindex disadvantages of @code{alloca}
2988 These are the disadvantages of @code{alloca} in comparison with
2989 @code{malloc}:
2991 @itemize @bullet
2992 @item
2993 If you try to allocate more memory than the machine can provide, you
2994 don't get a clean error message.  Instead you get a fatal signal like
2995 the one you would get from an infinite recursion; probably a
2996 segmentation violation (@pxref{Program Error Signals}).
2998 @item
2999 Some @nongnusystems{} fail to support @code{alloca}, so it is less
3000 portable.  However, a slower emulation of @code{alloca} written in C
3001 is available for use on systems with this deficiency.
3002 @end itemize
3004 @node GNU C Variable-Size Arrays
3005 @subsubsection GNU C Variable-Size Arrays
3006 @cindex variable-sized arrays
3008 In GNU C, you can replace most uses of @code{alloca} with an array of
3009 variable size.  Here is how @code{open2} would look then:
3011 @smallexample
3012 int open2 (char *str1, char *str2, int flags, int mode)
3014   char name[strlen (str1) + strlen (str2) + 1];
3015   stpcpy (stpcpy (name, str1), str2);
3016   return open (name, flags, mode);
3018 @end smallexample
3020 But @code{alloca} is not always equivalent to a variable-sized array, for
3021 several reasons:
3023 @itemize @bullet
3024 @item
3025 A variable size array's space is freed at the end of the scope of the
3026 name of the array.  The space allocated with @code{alloca}
3027 remains until the end of the function.
3029 @item
3030 It is possible to use @code{alloca} within a loop, allocating an
3031 additional block on each iteration.  This is impossible with
3032 variable-sized arrays.
3033 @end itemize
3035 @strong{NB:} If you mix use of @code{alloca} and variable-sized arrays
3036 within one function, exiting a scope in which a variable-sized array was
3037 declared frees all blocks allocated with @code{alloca} during the
3038 execution of that scope.
3041 @node Resizing the Data Segment
3042 @section Resizing the Data Segment
3044 The symbols in this section are declared in @file{unistd.h}.
3046 You will not normally use the functions in this section, because the
3047 functions described in @ref{Memory Allocation} are easier to use.  Those
3048 are interfaces to a @glibcadj{} memory allocator that uses the
3049 functions below itself.  The functions below are simple interfaces to
3050 system calls.
3052 @deftypefun int brk (void *@var{addr})
3053 @standards{BSD, unistd.h}
3054 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3056 @code{brk} sets the high end of the calling process' data segment to
3057 @var{addr}.
3059 The address of the end of a segment is defined to be the address of the
3060 last byte in the segment plus 1.
3062 The function has no effect if @var{addr} is lower than the low end of
3063 the data segment.  (This is considered success, by the way.)
3065 The function fails if it would cause the data segment to overlap another
3066 segment or exceed the process' data storage limit (@pxref{Limits on
3067 Resources}).
3069 The function is named for a common historical case where data storage
3070 and the stack are in the same segment.  Data storage allocation grows
3071 upward from the bottom of the segment while the stack grows downward
3072 toward it from the top of the segment and the curtain between them is
3073 called the @dfn{break}.
3075 The return value is zero on success.  On failure, the return value is
3076 @code{-1} and @code{errno} is set accordingly.  The following @code{errno}
3077 values are specific to this function:
3079 @table @code
3080 @item ENOMEM
3081 The request would cause the data segment to overlap another segment or
3082 exceed the process' data storage limit.
3083 @end table
3085 @c The Brk system call in Linux (as opposed to the GNU C Library function)
3086 @c is considerably different.  It always returns the new end of the data
3087 @c segment, whether it succeeds or fails.  The GNU C library Brk determines
3088 @c it's a failure if and only if the system call returns an address less
3089 @c than the address requested.
3091 @end deftypefun
3094 @deftypefun void *sbrk (ptrdiff_t @var{delta})
3095 @standards{BSD, unistd.h}
3096 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3098 This function is the same as @code{brk} except that you specify the new
3099 end of the data segment as an offset @var{delta} from the current end
3100 and on success the return value is the address of the resulting end of
3101 the data segment instead of zero.
3103 This means you can use @samp{sbrk(0)} to find out what the current end
3104 of the data segment is.
3106 @end deftypefun
3108 @node Memory Protection
3109 @section Memory Protection
3110 @cindex memory protection
3111 @cindex page protection
3112 @cindex protection flags
3114 When a page is mapped using @code{mmap}, page protection flags can be
3115 specified using the protection flags argument.  @xref{Memory-mapped
3116 I/O}.
3118 The following flags are available:
3120 @vtable @code
3121 @item PROT_WRITE
3122 @standards{POSIX, sys/mman.h}
3123 The memory can be written to.
3125 @item PROT_READ
3126 @standards{POSIX, sys/mman.h}
3127 The memory can be read.  On some architectures, this flag implies that
3128 the memory can be executed as well (as if @code{PROT_EXEC} had been
3129 specified at the same time).
3131 @item PROT_EXEC
3132 @standards{POSIX, sys/mman.h}
3133 The memory can be used to store instructions which can then be executed.
3134 On most architectures, this flag implies that the memory can be read (as
3135 if @code{PROT_READ} had been specified).
3137 @item PROT_NONE
3138 @standards{POSIX, sys/mman.h}
3139 This flag must be specified on its own.
3141 The memory is reserved, but cannot be read, written, or executed.  If
3142 this flag is specified in a call to @code{mmap}, a virtual memory area
3143 will be set aside for future use in the process, and @code{mmap} calls
3144 without the @code{MAP_FIXED} flag will not use it for subsequent
3145 allocations.  For anonymous mappings, the kernel will not reserve any
3146 physical memory for the allocation at the time the mapping is created.
3147 @end vtable
3149 The operating system may keep track of these flags separately even if
3150 the underlying hardware treats them the same for the purposes of access
3151 checking (as happens with @code{PROT_READ} and @code{PROT_EXEC} on some
3152 platforms).  On GNU systems, @code{PROT_EXEC} always implies
3153 @code{PROT_READ}, so that users can view the machine code which is
3154 executing on their system.
3156 Inappropriate access will cause a segfault (@pxref{Program Error
3157 Signals}).
3159 After allocation, protection flags can be changed using the
3160 @code{mprotect} function.
3162 @deftypefun int mprotect (void *@var{address}, size_t @var{length}, int @var{protection})
3163 @standards{POSIX, sys/mman.h}
3164 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3166 A successful call to the @code{mprotect} function changes the protection
3167 flags of at least @var{length} bytes of memory, starting at
3168 @var{address}.
3170 @var{address} must be aligned to the page size for the mapping.  The
3171 system page size can be obtained by calling @code{sysconf} with the
3172 @code{_SC_PAGESIZE} parameter (@pxref{Sysconf Definition}).  The system
3173 page size is the granularity in which the page protection of anonymous
3174 memory mappings and most file mappings can be changed.  Memory which is
3175 mapped from special files or devices may have larger page granularity
3176 than the system page size and may require larger alignment.
3178 @var{length} is the number of bytes whose protection flags must be
3179 changed.  It is automatically rounded up to the next multiple of the
3180 system page size.
3182 @var{protection} is a combination of the @code{PROT_*} flags described
3183 above.
3185 The @code{mprotect} function returns @math{0} on success and @math{-1}
3186 on failure.
3188 The following @code{errno} error conditions are defined for this
3189 function:
3191 @table @code
3192 @item ENOMEM
3193 The system was not able to allocate resources to fulfill the request.
3194 This can happen if there is not enough physical memory in the system for
3195 the allocation of backing storage.  The error can also occur if the new
3196 protection flags would cause the memory region to be split from its
3197 neighbors, and the process limit for the number of such distinct memory
3198 regions would be exceeded.
3200 @item EINVAL
3201 @var{address} is not properly aligned to a page boundary for the
3202 mapping, or @var{length} (after rounding up to the system page size) is
3203 not a multiple of the applicable page size for the mapping, or the
3204 combination of flags in @var{protection} is not valid.
3206 @item EACCES
3207 The file for a file-based mapping was not opened with open flags which
3208 are compatible with @var{protection}.
3210 @item EPERM
3211 The system security policy does not allow a mapping with the specified
3212 flags.  For example, mappings which are both @code{PROT_EXEC} and
3213 @code{PROT_WRITE} at the same time might not be allowed.
3214 @end table
3215 @end deftypefun
3217 If the @code{mprotect} function is used to make a region of memory
3218 inaccessible by specifying the @code{PROT_NONE} protection flag and
3219 access is later restored, the memory retains its previous contents.
3221 On some systems, it may not be possible to specify additional flags
3222 which were not present when the mapping was first created.  For example,
3223 an attempt to make a region of memory executable could fail if the
3224 initial protection flags were @samp{PROT_READ | PROT_WRITE}.
3226 In general, the @code{mprotect} function can be used to change any
3227 process memory, no matter how it was allocated.  However, portable use
3228 of the function requires that it is only used with memory regions
3229 returned by @code{mmap} or @code{mmap64}.
3231 @subsection Memory Protection Keys
3233 @cindex memory protection key
3234 @cindex protection key
3235 @cindex MPK
3236 On some systems, further restrictions can be added to specific pages
3237 using @dfn{memory protection keys}.  These restrictions work as follows:
3239 @itemize @bullet
3240 @item
3241 All memory pages are associated with a protection key.  The default
3242 protection key does not cause any additional protections to be applied
3243 during memory accesses.  New keys can be allocated with the
3244 @code{pkey_alloc} function, and applied to pages using
3245 @code{pkey_mprotect}.
3247 @item
3248 Each thread has a set of separate access right restriction for each
3249 protection key.  These access rights can be manipulated using the
3250 @code{pkey_set} and @code{pkey_get} functions.
3252 @item
3253 During a memory access, the system obtains the protection key for the
3254 accessed page and uses that to determine the applicable access rights,
3255 as configured for the current thread.  If the access is restricted, a
3256 segmentation fault is the result ((@pxref{Program Error Signals}).
3257 These checks happen in addition to the @code{PROT_}* protection flags
3258 set by @code{mprotect} or @code{pkey_mprotect}.
3259 @end itemize
3261 New threads and subprocesses inherit the access rights of the current
3262 thread.  If a protection key is allocated subsequently, existing threads
3263 (except the current) will use an unspecified system default for the
3264 access rights associated with newly allocated keys.
3266 Upon entering a signal handler, the system resets the access rights of
3267 the current thread so that pages with the default key can be accessed,
3268 but the access rights for other protection keys are unspecified.
3270 Applications are expected to allocate a key once using
3271 @code{pkey_alloc}, and apply the key to memory regions which need
3272 special protection with @code{pkey_mprotect}:
3274 @smallexample
3275   int key = pkey_alloc (0, PKEY_DISABLE_ACCESS);
3276   if (key < 0)
3277     /* Perform error checking, including fallback for lack of support.  */
3278     ...;
3280   /* Apply the key to a special memory region used to store critical
3281      data.  */
3282   if (pkey_mprotect (region, region_length,
3283                      PROT_READ | PROT_WRITE, key) < 0)
3284     ...; /* Perform error checking (generally fatal).  */
3285 @end smallexample
3287 If the key allocation fails due to lack of support for memory protection
3288 keys, the @code{pkey_mprotect} call can usually be skipped.  In this
3289 case, the region will not be protected by default.  It is also possible
3290 to call @code{pkey_mprotect} with a key value of @math{-1}, in which
3291 case it will behave in the same way as @code{mprotect}.
3293 After key allocation assignment to memory pages, @code{pkey_set} can be
3294 used to temporarily acquire access to the memory region and relinquish
3295 it again:
3297 @smallexample
3298   if (key >= 0 && pkey_set (key, 0) < 0)
3299     ...; /* Perform error checking (generally fatal).  */
3300   /* At this point, the current thread has read-write access to the
3301      memory region.  */
3302   ...
3303   /* Revoke access again.  */
3304   if (key >= 0 && pkey_set (key, PKEY_DISABLE_ACCESS) < 0)
3305     ...; /* Perform error checking (generally fatal).  */
3306 @end smallexample
3308 In this example, a negative key value indicates that no key had been
3309 allocated, which means that the system lacks support for memory
3310 protection keys and it is not necessary to change the the access rights
3311 of the current thread (because it always has access).
3313 Compared to using @code{mprotect} to change the page protection flags,
3314 this approach has two advantages: It is thread-safe in the sense that
3315 the access rights are only changed for the current thread, so another
3316 thread which changes its own access rights concurrently to gain access
3317 to the mapping will not suddenly see its access rights revoked.  And
3318 @code{pkey_set} typically does not involve a call into the kernel and a
3319 context switch, so it is more efficient.
3321 @deftypefun int pkey_alloc (unsigned int @var{flags}, unsigned int @var{restrictions})
3322 @standards{Linux, sys/mman.h}
3323 @safety{@prelim{}@mtsafe{}@assafe{}@acunsafe{@acucorrupt{}}}
3324 Allocate a new protection key.  The @var{flags} argument is reserved and
3325 must be zero.  The @var{restrictions} argument specifies access rights
3326 which are applied to the current thread (as if with @code{pkey_set}
3327 below).  Access rights of other threads are not changed.
3329 The function returns the new protection key, a non-negative number, or
3330 @math{-1} on error.
3332 The following @code{errno} error conditions are defined for this
3333 function:
3335 @table @code
3336 @item ENOSYS
3337 The system does not implement memory protection keys.
3339 @item EINVAL
3340 The @var{flags} argument is not zero.
3342 The @var{restrictions} argument is invalid.
3344 The system does not implement memory protection keys or runs in a mode
3345 in which memory protection keys are disabled.
3347 @item ENOSPC
3348 All available protection keys already have been allocated.
3350 The system does not implement memory protection keys or runs in a mode
3351 in which memory protection keys are disabled.
3353 @end table
3354 @end deftypefun
3356 @deftypefun int pkey_free (int @var{key})
3357 @standards{Linux, sys/mman.h}
3358 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3359 Deallocate the protection key, so that it can be reused by
3360 @code{pkey_alloc}.
3362 Calling this function does not change the access rights of the freed
3363 protection key.  The calling thread and other threads may retain access
3364 to it, even if it is subsequently allocated again.  For this reason, it
3365 is not recommended to call the @code{pkey_free} function.
3367 @table @code
3368 @item ENOSYS
3369 The system does not implement memory protection keys.
3371 @item EINVAL
3372 The @var{key} argument is not a valid protection key.
3373 @end table
3374 @end deftypefun
3376 @deftypefun int pkey_mprotect (void *@var{address}, size_t @var{length}, int @var{protection}, int @var{key})
3377 @standards{Linux, sys/mman.h}
3378 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3379 Similar to @code{mprotect}, but also set the memory protection key for
3380 the memory region to @code{key}.
3382 Some systems use memory protection keys to emulate certain combinations
3383 of @var{protection} flags.  Under such circumstances, specifying an
3384 explicit protection key may behave as if additional flags have been
3385 specified in @var{protection}, even though this does not happen with the
3386 default protection key.  For example, some systems can support
3387 @code{PROT_EXEC}-only mappings only with a default protection key, and
3388 memory with a key which was allocated using @code{pkey_alloc} will still
3389 be readable if @code{PROT_EXEC} is specified without @code{PROT_READ}.
3391 If @var{key} is @math{-1}, the default protection key is applied to the
3392 mapping, just as if @code{mprotect} had been called.
3394 The @code{pkey_mprotect} function returns @math{0} on success and
3395 @math{-1} on failure.  The same @code{errno} error conditions as for
3396 @code{mprotect} are defined for this function, with the following
3397 addition:
3399 @table @code
3400 @item EINVAL
3401 The @var{key} argument is not @math{-1} or a valid memory protection
3402 key allocated using @code{pkey_alloc}.
3404 @item ENOSYS
3405 The system does not implement memory protection keys, and @var{key} is
3406 not @math{-1}.
3407 @end table
3408 @end deftypefun
3410 @deftypefun int pkey_set (int @var{key}, unsigned int @var{rights})
3411 @standards{Linux, sys/mman.h}
3412 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3413 Change the access rights of the current thread for memory pages with the
3414 protection key @var{key} to @var{rights}.  If @var{rights} is zero, no
3415 additional access restrictions on top of the page protection flags are
3416 applied.  Otherwise, @var{rights} is a combination of the following
3417 flags:
3419 @vtable @code
3420 @item PKEY_DISABLE_WRITE
3421 @standards{Linux, sys/mman.h}
3422 Subsequent attempts to write to memory with the specified protection
3423 key will fault.
3425 @item PKEY_DISABLE_ACCESS
3426 @standards{Linux, sys/mman.h}
3427 Subsequent attempts to write to or read from memory with the specified
3428 protection key will fault.
3429 @end vtable
3431 Operations not specified as flags are not restricted.  In particular,
3432 this means that the memory region will remain executable if it was
3433 mapped with the @code{PROT_EXEC} protection flag and
3434 @code{PKEY_DISABLE_ACCESS} has been specified.
3436 Calling the @code{pkey_set} function with a protection key which was not
3437 allocated by @code{pkey_alloc} results in undefined behavior.  This
3438 means that calling this function on systems which do not support memory
3439 protection keys is undefined.
3441 The @code{pkey_set} function returns @math{0} on success and @math{-1}
3442 on failure.
3444 The following @code{errno} error conditions are defined for this
3445 function:
3447 @table @code
3448 @item EINVAL
3449 The system does not support the access rights restrictions expressed in
3450 the @var{rights} argument.
3451 @end table
3452 @end deftypefun
3454 @deftypefun int pkey_get (int @var{key})
3455 @standards{Linux, sys/mman.h}
3456 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3457 Return the access rights of the current thread for memory pages with
3458 protection key @var{key}.  The return value is zero or a combination of
3459 the @code{PKEY_DISABLE_}* flags; see the @code{pkey_set} function.
3461 Calling the @code{pkey_get} function with a protection key which was not
3462 allocated by @code{pkey_alloc} results in undefined behavior.  This
3463 means that calling this function on systems which do not support memory
3464 protection keys is undefined.
3465 @end deftypefun
3467 @node Locking Pages
3468 @section Locking Pages
3469 @cindex locking pages
3470 @cindex memory lock
3471 @cindex paging
3473 You can tell the system to associate a particular virtual memory page
3474 with a real page frame and keep it that way --- i.e., cause the page to
3475 be paged in if it isn't already and mark it so it will never be paged
3476 out and consequently will never cause a page fault.  This is called
3477 @dfn{locking} a page.
3479 The functions in this chapter lock and unlock the calling process'
3480 pages.
3482 @menu
3483 * Why Lock Pages::                Reasons to read this section.
3484 * Locked Memory Details::         Everything you need to know locked
3485                                     memory
3486 * Page Lock Functions::           Here's how to do it.
3487 @end menu
3489 @node Why Lock Pages
3490 @subsection Why Lock Pages
3492 Because page faults cause paged out pages to be paged in transparently,
3493 a process rarely needs to be concerned about locking pages.  However,
3494 there are two reasons people sometimes are:
3496 @itemize @bullet
3498 @item
3499 Speed.  A page fault is transparent only insofar as the process is not
3500 sensitive to how long it takes to do a simple memory access.  Time-critical
3501 processes, especially realtime processes, may not be able to wait or
3502 may not be able to tolerate variance in execution speed.
3503 @cindex realtime processing
3504 @cindex speed of execution
3506 A process that needs to lock pages for this reason probably also needs
3507 priority among other processes for use of the CPU.  @xref{Priority}.
3509 In some cases, the programmer knows better than the system's demand
3510 paging allocator which pages should remain in real memory to optimize
3511 system performance.  In this case, locking pages can help.
3513 @item
3514 Privacy.  If you keep secrets in virtual memory and that virtual memory
3515 gets paged out, that increases the chance that the secrets will get out.
3516 If a passphrase gets written out to disk swap space, for example, it might
3517 still be there long after virtual and real memory have been wiped clean.
3519 @end itemize
3521 Be aware that when you lock a page, that's one fewer page frame that can
3522 be used to back other virtual memory (by the same or other processes),
3523 which can mean more page faults, which means the system runs more
3524 slowly.  In fact, if you lock enough memory, some programs may not be
3525 able to run at all for lack of real memory.
3527 @node Locked Memory Details
3528 @subsection Locked Memory Details
3530 A memory lock is associated with a virtual page, not a real frame.  The
3531 paging rule is: If a frame backs at least one locked page, don't page it
3532 out.
3534 Memory locks do not stack.  I.e., you can't lock a particular page twice
3535 so that it has to be unlocked twice before it is truly unlocked.  It is
3536 either locked or it isn't.
3538 A memory lock persists until the process that owns the memory explicitly
3539 unlocks it.  (But process termination and exec cause the virtual memory
3540 to cease to exist, which you might say means it isn't locked any more).
3542 Memory locks are not inherited by child processes.  (But note that on a
3543 modern Unix system, immediately after a fork, the parent's and the
3544 child's virtual address space are backed by the same real page frames,
3545 so the child enjoys the parent's locks).  @xref{Creating a Process}.
3547 Because of its ability to impact other processes, only the superuser can
3548 lock a page.  Any process can unlock its own page.
3550 The system sets limits on the amount of memory a process can have locked
3551 and the amount of real memory it can have dedicated to it.  @xref{Limits
3552 on Resources}.
3554 In Linux, locked pages aren't as locked as you might think.
3555 Two virtual pages that are not shared memory can nonetheless be backed
3556 by the same real frame.  The kernel does this in the name of efficiency
3557 when it knows both virtual pages contain identical data, and does it
3558 even if one or both of the virtual pages are locked.
3560 But when a process modifies one of those pages, the kernel must get it a
3561 separate frame and fill it with the page's data.  This is known as a
3562 @dfn{copy-on-write page fault}.  It takes a small amount of time and in
3563 a pathological case, getting that frame may require I/O.
3564 @cindex copy-on-write page fault
3565 @cindex page fault, copy-on-write
3567 To make sure this doesn't happen to your program, don't just lock the
3568 pages.  Write to them as well, unless you know you won't write to them
3569 ever.  And to make sure you have pre-allocated frames for your stack,
3570 enter a scope that declares a C automatic variable larger than the
3571 maximum stack size you will need, set it to something, then return from
3572 its scope.
3574 @node Page Lock Functions
3575 @subsection Functions To Lock And Unlock Pages
3577 The symbols in this section are declared in @file{sys/mman.h}.  These
3578 functions are defined by POSIX.1b, but their availability depends on
3579 your kernel.  If your kernel doesn't allow these functions, they exist
3580 but always fail.  They @emph{are} available with a Linux kernel.
3582 @strong{Portability Note:} POSIX.1b requires that when the @code{mlock}
3583 and @code{munlock} functions are available, the file @file{unistd.h}
3584 define the macro @code{_POSIX_MEMLOCK_RANGE} and the file
3585 @code{limits.h} define the macro @code{PAGESIZE} to be the size of a
3586 memory page in bytes.  It requires that when the @code{mlockall} and
3587 @code{munlockall} functions are available, the @file{unistd.h} file
3588 define the macro @code{_POSIX_MEMLOCK}.  @Theglibc{} conforms to
3589 this requirement.
3591 @deftypefun int mlock (const void *@var{addr}, size_t @var{len})
3592 @standards{POSIX.1b, sys/mman.h}
3593 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3595 @code{mlock} locks a range of the calling process' virtual pages.
3597 The range of memory starts at address @var{addr} and is @var{len} bytes
3598 long.  Actually, since you must lock whole pages, it is the range of
3599 pages that include any part of the specified range.
3601 When the function returns successfully, each of those pages is backed by
3602 (connected to) a real frame (is resident) and is marked to stay that
3603 way.  This means the function may cause page-ins and have to wait for
3604 them.
3606 When the function fails, it does not affect the lock status of any
3607 pages.
3609 The return value is zero if the function succeeds.  Otherwise, it is
3610 @code{-1} and @code{errno} is set accordingly.  @code{errno} values
3611 specific to this function are:
3613 @table @code
3614 @item ENOMEM
3615 @itemize @bullet
3616 @item
3617 At least some of the specified address range does not exist in the
3618 calling process' virtual address space.
3619 @item
3620 The locking would cause the process to exceed its locked page limit.
3621 @end itemize
3623 @item EPERM
3624 The calling process is not superuser.
3626 @item EINVAL
3627 @var{len} is not positive.
3629 @item ENOSYS
3630 The kernel does not provide @code{mlock} capability.
3632 @end table
3633 @end deftypefun
3635 @deftypefun int mlock2 (const void *@var{addr}, size_t @var{len}, unsigned int @var{flags})
3636 @standards{Linux, sys/mman.h}
3637 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3639 This function is similar to @code{mlock}.  If @var{flags} is zero, a
3640 call to @code{mlock2} behaves exactly as the equivalent call to @code{mlock}.
3642 The @var{flags} argument must be a combination of zero or more of the
3643 following flags:
3645 @vtable @code
3646 @item MLOCK_ONFAULT
3647 @standards{Linux, sys/mman.h}
3648 Only those pages in the specified address range which are already in
3649 memory are locked immediately.  Additional pages in the range are
3650 automatically locked in case of a page fault and allocation of memory.
3651 @end vtable
3653 Like @code{mlock}, @code{mlock2} returns zero on success and @code{-1}
3654 on failure, setting @code{errno} accordingly.  Additional @code{errno}
3655 values defined for @code{mlock2} are:
3657 @table @code
3658 @item EINVAL
3659 The specified (non-zero) @var{flags} argument is not supported by this
3660 system.
3661 @end table
3662 @end deftypefun
3664 You can lock @emph{all} a process' memory with @code{mlockall}.  You
3665 unlock memory with @code{munlock} or @code{munlockall}.
3667 To avoid all page faults in a C program, you have to use
3668 @code{mlockall}, because some of the memory a program uses is hidden
3669 from the C code, e.g. the stack and automatic variables, and you
3670 wouldn't know what address to tell @code{mlock}.
3672 @deftypefun int munlock (const void *@var{addr}, size_t @var{len})
3673 @standards{POSIX.1b, sys/mman.h}
3674 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3676 @code{munlock} unlocks a range of the calling process' virtual pages.
3678 @code{munlock} is the inverse of @code{mlock} and functions completely
3679 analogously to @code{mlock}, except that there is no @code{EPERM}
3680 failure.
3682 @end deftypefun
3684 @deftypefun int mlockall (int @var{flags})
3685 @standards{POSIX.1b, sys/mman.h}
3686 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3688 @code{mlockall} locks all the pages in a process' virtual memory address
3689 space, and/or any that are added to it in the future.  This includes the
3690 pages of the code, data and stack segment, as well as shared libraries,
3691 user space kernel data, shared memory, and memory mapped files.
3693 @var{flags} is a string of single bit flags represented by the following
3694 macros.  They tell @code{mlockall} which of its functions you want.  All
3695 other bits must be zero.
3697 @vtable @code
3699 @item MCL_CURRENT
3700 Lock all pages which currently exist in the calling process' virtual
3701 address space.
3703 @item MCL_FUTURE
3704 Set a mode such that any pages added to the process' virtual address
3705 space in the future will be locked from birth.  This mode does not
3706 affect future address spaces owned by the same process so exec, which
3707 replaces a process' address space, wipes out @code{MCL_FUTURE}.
3708 @xref{Executing a File}.
3710 @end vtable
3712 When the function returns successfully, and you specified
3713 @code{MCL_CURRENT}, all of the process' pages are backed by (connected
3714 to) real frames (they are resident) and are marked to stay that way.
3715 This means the function may cause page-ins and have to wait for them.
3717 When the process is in @code{MCL_FUTURE} mode because it successfully
3718 executed this function and specified @code{MCL_CURRENT}, any system call
3719 by the process that requires space be added to its virtual address space
3720 fails with @code{errno} = @code{ENOMEM} if locking the additional space
3721 would cause the process to exceed its locked page limit.  In the case
3722 that the address space addition that can't be accommodated is stack
3723 expansion, the stack expansion fails and the kernel sends a
3724 @code{SIGSEGV} signal to the process.
3726 When the function fails, it does not affect the lock status of any pages
3727 or the future locking mode.
3729 The return value is zero if the function succeeds.  Otherwise, it is
3730 @code{-1} and @code{errno} is set accordingly.  @code{errno} values
3731 specific to this function are:
3733 @table @code
3734 @item ENOMEM
3735 @itemize @bullet
3736 @item
3737 At least some of the specified address range does not exist in the
3738 calling process' virtual address space.
3739 @item
3740 The locking would cause the process to exceed its locked page limit.
3741 @end itemize
3743 @item EPERM
3744 The calling process is not superuser.
3746 @item EINVAL
3747 Undefined bits in @var{flags} are not zero.
3749 @item ENOSYS
3750 The kernel does not provide @code{mlockall} capability.
3752 @end table
3754 You can lock just specific pages with @code{mlock}.  You unlock pages
3755 with @code{munlockall} and @code{munlock}.
3757 @end deftypefun
3760 @deftypefun int munlockall (void)
3761 @standards{POSIX.1b, sys/mman.h}
3762 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3764 @code{munlockall} unlocks every page in the calling process' virtual
3765 address space and turns off @code{MCL_FUTURE} future locking mode.
3767 The return value is zero if the function succeeds.  Otherwise, it is
3768 @code{-1} and @code{errno} is set accordingly.  The only way this
3769 function can fail is for generic reasons that all functions and system
3770 calls can fail, so there are no specific @code{errno} values.
3772 @end deftypefun
3777 @ignore
3778 @c This was never actually implemented.  -zw
3779 @node Relocating Allocator
3780 @section Relocating Allocator
3782 @cindex relocating memory allocator
3783 Any system of dynamic memory allocation has overhead: the amount of
3784 space it uses is more than the amount the program asks for.  The
3785 @dfn{relocating memory allocator} achieves very low overhead by moving
3786 blocks in memory as necessary, on its own initiative.
3788 @c @menu
3789 @c * Relocator Concepts::               How to understand relocating allocation.
3790 @c * Using Relocator::          Functions for relocating allocation.
3791 @c @end menu
3793 @node Relocator Concepts
3794 @subsection Concepts of Relocating Allocation
3796 @ifinfo
3797 The @dfn{relocating memory allocator} achieves very low overhead by
3798 moving blocks in memory as necessary, on its own initiative.
3799 @end ifinfo
3801 When you allocate a block with @code{malloc}, the address of the block
3802 never changes unless you use @code{realloc} to change its size.  Thus,
3803 you can safely store the address in various places, temporarily or
3804 permanently, as you like.  This is not safe when you use the relocating
3805 memory allocator, because any and all relocatable blocks can move
3806 whenever you allocate memory in any fashion.  Even calling @code{malloc}
3807 or @code{realloc} can move the relocatable blocks.
3809 @cindex handle
3810 For each relocatable block, you must make a @dfn{handle}---a pointer
3811 object in memory, designated to store the address of that block.  The
3812 relocating allocator knows where each block's handle is, and updates the
3813 address stored there whenever it moves the block, so that the handle
3814 always points to the block.  Each time you access the contents of the
3815 block, you should fetch its address anew from the handle.
3817 To call any of the relocating allocator functions from a signal handler
3818 is almost certainly incorrect, because the signal could happen at any
3819 time and relocate all the blocks.  The only way to make this safe is to
3820 block the signal around any access to the contents of any relocatable
3821 block---not a convenient mode of operation.  @xref{Nonreentrancy}.
3823 @node Using Relocator
3824 @subsection Allocating and Freeing Relocatable Blocks
3826 @pindex malloc.h
3827 In the descriptions below, @var{handleptr} designates the address of the
3828 handle.  All the functions are declared in @file{malloc.h}; all are GNU
3829 extensions.
3831 @comment malloc.h
3832 @comment GNU
3833 @c @deftypefun {void *} r_alloc (void **@var{handleptr}, size_t @var{size})
3834 This function allocates a relocatable block of size @var{size}.  It
3835 stores the block's address in @code{*@var{handleptr}} and returns
3836 a non-null pointer to indicate success.
3838 If @code{r_alloc} can't get the space needed, it stores a null pointer
3839 in @code{*@var{handleptr}}, and returns a null pointer.
3840 @end deftypefun
3842 @comment malloc.h
3843 @comment GNU
3844 @c @deftypefun void r_alloc_free (void **@var{handleptr})
3845 This function is the way to free a relocatable block.  It frees the
3846 block that @code{*@var{handleptr}} points to, and stores a null pointer
3847 in @code{*@var{handleptr}} to show it doesn't point to an allocated
3848 block any more.
3849 @end deftypefun
3851 @comment malloc.h
3852 @comment GNU
3853 @c @deftypefun {void *} r_re_alloc (void **@var{handleptr}, size_t @var{size})
3854 The function @code{r_re_alloc} adjusts the size of the block that
3855 @code{*@var{handleptr}} points to, making it @var{size} bytes long.  It
3856 stores the address of the resized block in @code{*@var{handleptr}} and
3857 returns a non-null pointer to indicate success.
3859 If enough memory is not available, this function returns a null pointer
3860 and does not modify @code{*@var{handleptr}}.
3861 @end deftypefun
3862 @end ignore
3867 @ignore
3868 @comment No longer available...
3870 @comment @node Memory Warnings
3871 @comment @section Memory Usage Warnings
3872 @comment @cindex memory usage warnings
3873 @comment @cindex warnings of memory almost full
3875 @pindex malloc.c
3876 You can ask for warnings as the program approaches running out of memory
3877 space, by calling @code{memory_warnings}.  This tells @code{malloc} to
3878 check memory usage every time it asks for more memory from the operating
3879 system.  This is a GNU extension declared in @file{malloc.h}.
3881 @comment malloc.h
3882 @comment GNU
3883 @comment @deftypefun void memory_warnings (void *@var{start}, void (*@var{warn-func}) (const char *))
3884 Call this function to request warnings for nearing exhaustion of virtual
3885 memory.
3887 The argument @var{start} says where data space begins, in memory.  The
3888 allocator compares this against the last address used and against the
3889 limit of data space, to determine the fraction of available memory in
3890 use.  If you supply zero for @var{start}, then a default value is used
3891 which is right in most circumstances.
3893 For @var{warn-func}, supply a function that @code{malloc} can call to
3894 warn you.  It is called with a string (a warning message) as argument.
3895 Normally it ought to display the string for the user to read.
3896 @end deftypefun
3898 The warnings come when memory becomes 75% full, when it becomes 85%
3899 full, and when it becomes 95% full.  Above 95% you get another warning
3900 each time memory usage increases.
3902 @end ignore