NEWS: Add advisories.
[glibc.git] / manual / memory.texi
blob3710d7ec667519ccd72debd5bbce06fd0ab4444c
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 * Statistics of Malloc::        Getting information about how much
332                                  memory your program is using.
333 * Summary of Malloc::           Summary of @code{malloc} and related functions.
334 @end menu
336 @node Basic Allocation
337 @subsubsection Basic Memory Allocation
338 @cindex allocation of memory with @code{malloc}
340 To allocate a block of memory, call @code{malloc}.  The prototype for
341 this function is in @file{stdlib.h}.
342 @pindex stdlib.h
344 @deftypefun {void *} malloc (size_t @var{size})
345 @standards{ISO, malloc.h}
346 @standards{ISO, stdlib.h}
347 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
348 @c Malloc hooks and __morecore pointers, as well as such parameters as
349 @c max_n_mmaps and max_mmapped_mem, are accessed without guards, so they
350 @c could pose a thread safety issue; in order to not declare malloc
351 @c MT-unsafe, it's modifying the hooks and parameters while multiple
352 @c threads are active that is regarded as unsafe.  An arena's next field
353 @c is initialized and never changed again, except for main_arena's,
354 @c that's protected by list_lock; next_free is only modified while
355 @c list_lock is held too.  All other data members of an arena, as well
356 @c as the metadata of the memory areas assigned to it, are only modified
357 @c while holding the arena's mutex (fastbin pointers use catomic ops
358 @c because they may be modified by free without taking the arena's
359 @c lock).  Some reassurance was needed for fastbins, for it wasn't clear
360 @c how they were initialized.  It turns out they are always
361 @c zero-initialized: main_arena's, for being static data, and other
362 @c arena's, for being just-mmapped memory.
364 @c Leaking file descriptors and memory in case of cancellation is
365 @c unavoidable without disabling cancellation, but the lock situation is
366 @c a bit more complicated: we don't have fallback arenas for malloc to
367 @c be safe to call from within signal handlers.  Error-checking mutexes
368 @c or trylock could enable us to try and use alternate arenas, even with
369 @c -DPER_THREAD (enabled by default), but supporting interruption
370 @c (cancellation or signal handling) while holding the arena list mutex
371 @c would require more work; maybe blocking signals and disabling async
372 @c cancellation while manipulating the arena lists?
374 @c __libc_malloc @asulock @aculock @acsfd @acsmem
375 @c  force_reg ok
376 @c  *malloc_hook unguarded
377 @c  arena_lock @asulock @aculock @acsfd @acsmem
378 @c   mutex_lock @asulock @aculock
379 @c   arena_get2 @asulock @aculock @acsfd @acsmem
380 @c    get_free_list @asulock @aculock
381 @c     mutex_lock (list_lock) dup @asulock @aculock
382 @c     mutex_unlock (list_lock) dup @aculock
383 @c     mutex_lock (arena lock) dup @asulock @aculock [returns locked]
384 @c    __get_nprocs ext ok @acsfd
385 @c    NARENAS_FROM_NCORES ok
386 @c    catomic_compare_and_exchange_bool_acq ok
387 @c    _int_new_arena ok @asulock @aculock @acsmem
388 @c     new_heap ok @acsmem
389 @c      mmap ok @acsmem
390 @c      munmap ok @acsmem
391 @c      mprotect ok
392 @c     chunk2mem ok
393 @c     set_head ok
394 @c     tsd_setspecific dup ok
395 @c     mutex_init ok
396 @c     mutex_lock (just-created mutex) ok, returns locked
397 @c     mutex_lock (list_lock) dup @asulock @aculock
398 @c     atomic_write_barrier ok
399 @c     mutex_unlock (list_lock) @aculock
400 @c    catomic_decrement ok
401 @c    reused_arena @asulock @aculock
402 @c      reads&writes next_to_use and iterates over arena next without guards
403 @c      those are harmless as long as we don't drop arenas from the
404 @c      NEXT list, and we never do; when a thread terminates,
405 @c      __malloc_arena_thread_freeres prepends the arena to the free_list
406 @c      NEXT_FREE list, but NEXT is never modified, so it's safe!
407 @c     mutex_trylock (arena lock) @asulock @aculock
408 @c     mutex_lock (arena lock) dup @asulock @aculock
409 @c     tsd_setspecific dup ok
410 @c  _int_malloc @acsfd @acsmem
411 @c   checked_request2size ok
412 @c    REQUEST_OUT_OF_RANGE ok
413 @c    request2size ok
414 @c   get_max_fast ok
415 @c   fastbin_index ok
416 @c   fastbin ok
417 @c   catomic_compare_and_exhange_val_acq ok
418 @c   malloc_printerr dup @mtsenv
419 @c     if we get to it, we're toast already, undefined behavior must have
420 @c     been invoked before
421 @c    libc_message @mtsenv [no leaks with cancellation disabled]
422 @c     FATAL_PREPARE ok
423 @c      pthread_setcancelstate disable ok
424 @c     libc_secure_getenv @mtsenv
425 @c      getenv @mtsenv
426 @c     open_not_cancel_2 dup @acsfd
427 @c     strchrnul ok
428 @c     WRITEV_FOR_FATAL ok
429 @c      writev ok
430 @c     mmap ok @acsmem
431 @c     munmap ok @acsmem
432 @c     BEFORE_ABORT @acsfd
433 @c      backtrace ok
434 @c      write_not_cancel dup ok
435 @c      backtrace_symbols_fd @aculock
436 @c      open_not_cancel_2 dup @acsfd
437 @c      read_not_cancel dup ok
438 @c      close_not_cancel_no_status dup @acsfd
439 @c     abort ok
440 @c    itoa_word ok
441 @c    abort ok
442 @c   check_remalloced_chunk ok/disabled
443 @c   chunk2mem dup ok
444 @c   alloc_perturb ok
445 @c   in_smallbin_range ok
446 @c   smallbin_index ok
447 @c   bin_at ok
448 @c   last ok
449 @c   malloc_consolidate ok
450 @c    get_max_fast dup ok
451 @c    clear_fastchunks ok
452 @c    unsorted_chunks dup ok
453 @c    fastbin dup ok
454 @c    atomic_exchange_acquire ok
455 @c    check_inuse_chunk dup ok/disabled
456 @c    chunk_at_offset dup ok
457 @c    chunksize dup ok
458 @c    inuse_bit_at_offset dup ok
459 @c    unlink dup ok
460 @c    clear_inuse_bit_at_offset dup ok
461 @c    in_smallbin_range dup ok
462 @c    set_head dup ok
463 @c    malloc_init_state ok
464 @c     bin_at dup ok
465 @c     set_noncontiguous dup ok
466 @c     set_max_fast dup ok
467 @c     initial_top ok
468 @c      unsorted_chunks dup ok
469 @c    check_malloc_state ok/disabled
470 @c   set_inuse_bit_at_offset ok
471 @c   check_malloced_chunk ok/disabled
472 @c   largebin_index ok
473 @c   have_fastchunks ok
474 @c   unsorted_chunks ok
475 @c    bin_at ok
476 @c   chunksize ok
477 @c   chunk_at_offset ok
478 @c   set_head ok
479 @c   set_foot ok
480 @c   mark_bin ok
481 @c    idx2bit ok
482 @c   first ok
483 @c   unlink ok
484 @c    malloc_printerr dup ok
485 @c    in_smallbin_range dup ok
486 @c   idx2block ok
487 @c   idx2bit dup ok
488 @c   next_bin ok
489 @c   sysmalloc @acsfd @acsmem
490 @c    MMAP @acsmem
491 @c    set_head dup ok
492 @c    check_chunk ok/disabled
493 @c    chunk2mem dup ok
494 @c    chunksize dup ok
495 @c    chunk_at_offset dup ok
496 @c    heap_for_ptr ok
497 @c    grow_heap ok
498 @c     mprotect ok
499 @c    set_head dup ok
500 @c    new_heap @acsmem
501 @c     MMAP dup @acsmem
502 @c     munmap @acsmem
503 @c    top ok
504 @c    set_foot dup ok
505 @c    contiguous ok
506 @c    MORECORE ok
507 @c     *__morecore ok unguarded
508 @c      __default_morecore
509 @c       sbrk ok
510 @c    force_reg dup ok
511 @c    *__after_morecore_hook unguarded
512 @c    set_noncontiguous ok
513 @c    malloc_printerr dup ok
514 @c    _int_free (have_lock) @acsfd @acsmem [@asulock @aculock]
515 @c     chunksize dup ok
516 @c     mutex_unlock dup @aculock/!have_lock
517 @c     malloc_printerr dup ok
518 @c     check_inuse_chunk ok/disabled
519 @c     chunk_at_offset dup ok
520 @c     mutex_lock dup @asulock @aculock/@have_lock
521 @c     chunk2mem dup ok
522 @c     free_perturb ok
523 @c     set_fastchunks ok
524 @c      catomic_and ok
525 @c     fastbin_index dup ok
526 @c     fastbin dup ok
527 @c     catomic_compare_and_exchange_val_rel ok
528 @c     chunk_is_mmapped ok
529 @c     contiguous dup ok
530 @c     prev_inuse ok
531 @c     unlink dup ok
532 @c     inuse_bit_at_offset dup ok
533 @c     clear_inuse_bit_at_offset ok
534 @c     unsorted_chunks dup ok
535 @c     in_smallbin_range dup ok
536 @c     set_head dup ok
537 @c     set_foot dup ok
538 @c     check_free_chunk ok/disabled
539 @c     check_chunk dup ok/disabled
540 @c     have_fastchunks dup ok
541 @c     malloc_consolidate dup ok
542 @c     systrim ok
543 @c      MORECORE dup ok
544 @c      *__after_morecore_hook dup unguarded
545 @c      set_head dup ok
546 @c      check_malloc_state ok/disabled
547 @c     top dup ok
548 @c     heap_for_ptr dup ok
549 @c     heap_trim @acsfd @acsmem
550 @c      top dup ok
551 @c      chunk_at_offset dup ok
552 @c      prev_chunk ok
553 @c      chunksize dup ok
554 @c      prev_inuse dup ok
555 @c      delete_heap @acsmem
556 @c       munmap dup @acsmem
557 @c      unlink dup ok
558 @c      set_head dup ok
559 @c      shrink_heap @acsfd
560 @c       check_may_shrink_heap @acsfd
561 @c        open_not_cancel_2 @acsfd
562 @c        read_not_cancel ok
563 @c        close_not_cancel_no_status @acsfd
564 @c       MMAP dup ok
565 @c       madvise ok
566 @c     munmap_chunk @acsmem
567 @c      chunksize dup ok
568 @c      chunk_is_mmapped dup ok
569 @c      chunk2mem dup ok
570 @c      malloc_printerr dup ok
571 @c      munmap dup @acsmem
572 @c    check_malloc_state ok/disabled
573 @c  arena_get_retry @asulock @aculock @acsfd @acsmem
574 @c   mutex_unlock dup @aculock
575 @c   mutex_lock dup @asulock @aculock
576 @c   arena_get2 dup @asulock @aculock @acsfd @acsmem
577 @c  mutex_unlock @aculock
578 @c  mem2chunk ok
579 @c  chunk_is_mmapped ok
580 @c  arena_for_chunk ok
581 @c   chunk_non_main_arena ok
582 @c   heap_for_ptr ok
583 This function returns a pointer to a newly allocated block @var{size}
584 bytes long, or a null pointer (setting @code{errno})
585 if the block could not be allocated.
586 @end deftypefun
588 The contents of the block are undefined; you must initialize it yourself
589 (or use @code{calloc} instead; @pxref{Allocating Cleared Space}).
590 Normally you would convert the value to a pointer to the kind of object
591 that you want to store in the block.  Here we show an example of doing
592 so, and of initializing the space with zeros using the library function
593 @code{memset} (@pxref{Copying Strings and Arrays}):
595 @smallexample
596 struct foo *ptr = malloc (sizeof *ptr);
597 if (ptr == 0) abort ();
598 memset (ptr, 0, sizeof (struct foo));
599 @end smallexample
601 You can store the result of @code{malloc} into any pointer variable
602 without a cast, because @w{ISO C} automatically converts the type
603 @code{void *} to another type of pointer when necessary.  However, a cast
604 is necessary if the type is needed but not specified by context.
606 Remember that when allocating space for a string, the argument to
607 @code{malloc} must be one plus the length of the string.  This is
608 because a string is terminated with a null character that doesn't count
609 in the ``length'' of the string but does need space.  For example:
611 @smallexample
612 char *ptr = malloc (length + 1);
613 @end smallexample
615 @noindent
616 @xref{Representation of Strings}, for more information about this.
618 @node Malloc Examples
619 @subsubsection Examples of @code{malloc}
621 If no more space is available, @code{malloc} returns a null pointer.
622 You should check the value of @emph{every} call to @code{malloc}.  It is
623 useful to write a subroutine that calls @code{malloc} and reports an
624 error if the value is a null pointer, returning only if the value is
625 nonzero.  This function is conventionally called @code{xmalloc}.  Here
626 it is:
627 @cindex @code{xmalloc} function
629 @smallexample
630 void *
631 xmalloc (size_t size)
633   void *value = malloc (size);
634   if (value == 0)
635     fatal ("virtual memory exhausted");
636   return value;
638 @end smallexample
640 Here is a real example of using @code{malloc} (by way of @code{xmalloc}).
641 The function @code{savestring} will copy a sequence of characters into
642 a newly allocated null-terminated string:
644 @smallexample
645 @group
646 char *
647 savestring (const char *ptr, size_t len)
649   char *value = xmalloc (len + 1);
650   value[len] = '\0';
651   return memcpy (value, ptr, len);
653 @end group
654 @end smallexample
656 The block that @code{malloc} gives you is guaranteed to be aligned so
657 that it can hold any type of data.  On @gnusystems{}, the address is
658 always a multiple of eight on 32-bit systems, and a multiple of 16 on
659 64-bit systems.  Only rarely is any higher boundary (such as a page
660 boundary) necessary; for those cases, use @code{aligned_alloc} or
661 @code{posix_memalign} (@pxref{Aligned Memory Blocks}).
663 Note that the memory located after the end of the block is likely to be
664 in use for something else; perhaps a block already allocated by another
665 call to @code{malloc}.  If you attempt to treat the block as longer than
666 you asked for it to be, you are liable to destroy the data that
667 @code{malloc} uses to keep track of its blocks, or you may destroy the
668 contents of another block.  If you have already allocated a block and
669 discover you want it to be bigger, use @code{realloc} (@pxref{Changing
670 Block Size}).
672 @strong{Portability Notes:}
674 @itemize @bullet
675 @item
676 In @theglibc{}, a successful @code{malloc (0)}
677 returns a non-null pointer to a newly allocated size-zero block;
678 other implementations may return @code{NULL} instead.
679 POSIX and the ISO C standard allow both behaviors.
681 @item
682 In @theglibc{}, a failed @code{malloc} call sets @code{errno},
683 but ISO C does not require this and non-POSIX implementations
684 need not set @code{errno} when failing.
686 @item
687 In @theglibc{}, @code{malloc} always fails when @var{size} exceeds
688 @code{PTRDIFF_MAX}, to avoid problems with programs that subtract
689 pointers or use signed indexes.  Other implementations may succeed in
690 this case, leading to undefined behavior later.
691 @end itemize
693 @node Freeing after Malloc
694 @subsubsection Freeing Memory Allocated with @code{malloc}
695 @cindex freeing memory allocated with @code{malloc}
696 @cindex heap, freeing memory from
698 When you no longer need a block that you got with @code{malloc}, use the
699 function @code{free} to make the block available to be allocated again.
700 The prototype for this function is in @file{stdlib.h}.
701 @pindex stdlib.h
703 @deftypefun void free (void *@var{ptr})
704 @standards{ISO, malloc.h}
705 @standards{ISO, stdlib.h}
706 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
707 @c __libc_free @asulock @aculock @acsfd @acsmem
708 @c   releasing memory into fastbins modifies the arena without taking
709 @c   its mutex, but catomic operations ensure safety.  If two (or more)
710 @c   threads are running malloc and have their own arenas locked when
711 @c   each gets a signal whose handler free()s large (non-fastbin-able)
712 @c   blocks from each other's arena, we deadlock; this is a more general
713 @c   case of @asulock.
714 @c  *__free_hook unguarded
715 @c  mem2chunk ok
716 @c  chunk_is_mmapped ok, chunk bits not modified after allocation
717 @c  chunksize ok
718 @c  munmap_chunk dup @acsmem
719 @c  arena_for_chunk dup ok
720 @c  _int_free (!have_lock) dup @asulock @aculock @acsfd @acsmem
721 The @code{free} function deallocates the block of memory pointed at
722 by @var{ptr}.
723 @end deftypefun
725 Freeing a block alters the contents of the block.  @strong{Do not expect to
726 find any data (such as a pointer to the next block in a chain of blocks) in
727 the block after freeing it.}  Copy whatever you need out of the block before
728 freeing it!  Here is an example of the proper way to free all the blocks in
729 a chain, and the strings that they point to:
731 @smallexample
732 struct chain
733   @{
734     struct chain *next;
735     char *name;
736   @}
738 void
739 free_chain (struct chain *chain)
741   while (chain != 0)
742     @{
743       struct chain *next = chain->next;
744       free (chain->name);
745       free (chain);
746       chain = next;
747     @}
749 @end smallexample
751 Occasionally, @code{free} can actually return memory to the operating
752 system and make the process smaller.  Usually, all it can do is allow a
753 later call to @code{malloc} to reuse the space.  In the meantime, the
754 space remains in your program as part of a free-list used internally by
755 @code{malloc}.
757 The @code{free} function preserves the value of @code{errno}, so that
758 cleanup code need not worry about saving and restoring @code{errno}
759 around a call to @code{free}.  Although neither @w{ISO C} nor
760 POSIX.1-2017 requires @code{free} to preserve @code{errno}, a future
761 version of POSIX is planned to require it.
763 There is no point in freeing blocks at the end of a program, because all
764 of the program's space is given back to the system when the process
765 terminates.
767 @node Changing Block Size
768 @subsubsection Changing the Size of a Block
769 @cindex changing the size of a block (@code{malloc})
771 Often you do not know for certain how big a block you will ultimately need
772 at the time you must begin to use the block.  For example, the block might
773 be a buffer that you use to hold a line being read from a file; no matter
774 how long you make the buffer initially, you may encounter a line that is
775 longer.
777 You can make the block longer by calling @code{realloc} or
778 @code{reallocarray}.  These functions are declared in @file{stdlib.h}.
779 @pindex stdlib.h
781 @deftypefun {void *} realloc (void *@var{ptr}, size_t @var{newsize})
782 @standards{ISO, malloc.h}
783 @standards{ISO, stdlib.h}
784 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
785 @c It may call the implementations of malloc and free, so all of their
786 @c issues arise, plus the realloc hook, also accessed without guards.
788 @c __libc_realloc @asulock @aculock @acsfd @acsmem
789 @c  *__realloc_hook unguarded
790 @c  __libc_free dup @asulock @aculock @acsfd @acsmem
791 @c  __libc_malloc dup @asulock @aculock @acsfd @acsmem
792 @c  mem2chunk dup ok
793 @c  chunksize dup ok
794 @c  malloc_printerr dup ok
795 @c  checked_request2size dup ok
796 @c  chunk_is_mmapped dup ok
797 @c  mremap_chunk
798 @c   chunksize dup ok
799 @c   __mremap ok
800 @c   set_head dup ok
801 @c  MALLOC_COPY ok
802 @c   memcpy ok
803 @c  munmap_chunk dup @acsmem
804 @c  arena_for_chunk dup ok
805 @c  mutex_lock (arena mutex) dup @asulock @aculock
806 @c  _int_realloc @acsfd @acsmem
807 @c   malloc_printerr dup ok
808 @c   check_inuse_chunk dup ok/disabled
809 @c   chunk_at_offset dup ok
810 @c   chunksize dup ok
811 @c   set_head_size dup ok
812 @c   chunk_at_offset dup ok
813 @c   set_head dup ok
814 @c   chunk2mem dup ok
815 @c   inuse dup ok
816 @c   unlink dup ok
817 @c   _int_malloc dup @acsfd @acsmem
818 @c   mem2chunk dup ok
819 @c   MALLOC_COPY dup ok
820 @c   _int_free (have_lock) dup @acsfd @acsmem
821 @c   set_inuse_bit_at_offset dup ok
822 @c   set_head dup ok
823 @c  mutex_unlock (arena mutex) dup @aculock
824 @c  _int_free (!have_lock) dup @asulock @aculock @acsfd @acsmem
826 The @code{realloc} function changes the size of the block whose address is
827 @var{ptr} to be @var{newsize}.
829 Since the space after the end of the block may be in use, @code{realloc}
830 may find it necessary to copy the block to a new address where more free
831 space is available.  The value of @code{realloc} is the new address of the
832 block.  If the block needs to be moved, @code{realloc} copies the old
833 contents.
835 If you pass a null pointer for @var{ptr}, @code{realloc} behaves just
836 like @samp{malloc (@var{newsize})}.
837 Otherwise, if @var{newsize} is zero
838 @code{realloc} frees the block and returns @code{NULL}.
839 Otherwise, if @code{realloc} cannot reallocate the requested size
840 it returns @code{NULL} and sets @code{errno}; the original block
841 is left undisturbed.
842 @end deftypefun
844 @deftypefun {void *} reallocarray (void *@var{ptr}, size_t @var{nmemb}, size_t @var{size})
845 @standards{BSD, malloc.h}
846 @standards{BSD, stdlib.h}
847 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
849 The @code{reallocarray} function changes the size of the block whose address
850 is @var{ptr} to be long enough to contain a vector of @var{nmemb} elements,
851 each of size @var{size}.  It is equivalent to @samp{realloc (@var{ptr},
852 @var{nmemb} * @var{size})}, except that @code{reallocarray} fails safely if
853 the multiplication overflows, by setting @code{errno} to @code{ENOMEM},
854 returning a null pointer, and leaving the original block unchanged.
856 @code{reallocarray} should be used instead of @code{realloc} when the new size
857 of the allocated block is the result of a multiplication that might overflow.
859 @strong{Portability Note:} This function is not part of any standard.  It was
860 first introduced in OpenBSD 5.6.
861 @end deftypefun
863 Like @code{malloc}, @code{realloc} and @code{reallocarray} may return a null
864 pointer if no memory space is available to make the block bigger.  When this
865 happens, the original block is untouched; it has not been modified or
866 relocated.
868 In most cases it makes no difference what happens to the original block
869 when @code{realloc} fails, because the application program cannot continue
870 when it is out of memory, and the only thing to do is to give a fatal error
871 message.  Often it is convenient to write and use subroutines,
872 conventionally called @code{xrealloc} and @code{xreallocarray},
873 that take care of the error message
874 as @code{xmalloc} does for @code{malloc}:
875 @cindex @code{xrealloc} and @code{xreallocarray} functions
877 @smallexample
878 void *
879 xreallocarray (void *ptr, size_t nmemb, size_t size)
881   void *value = reallocarray (ptr, nmemb, size);
882   if (value == 0)
883     fatal ("Virtual memory exhausted");
884   return value;
887 void *
888 xrealloc (void *ptr, size_t size)
890   return xreallocarray (ptr, 1, size);
892 @end smallexample
894 You can also use @code{realloc} or @code{reallocarray} to make a block
895 smaller.  The reason you would do this is to avoid tying up a lot of memory
896 space when only a little is needed.
897 @comment The following is no longer true with the new malloc.
898 @comment But it seems wise to keep the warning for other implementations.
899 In several allocation implementations, making a block smaller sometimes
900 necessitates copying it, so it can fail if no other space is available.
902 @strong{Portability Notes:}
904 @itemize @bullet
905 @item
906 Portable programs should not attempt to reallocate blocks to be size zero.
907 On other implementations if @var{ptr} is non-null, @code{realloc (ptr, 0)}
908 might free the block and return a non-null pointer to a size-zero
909 object, or it might fail and return @code{NULL} without freeing the block.
910 The ISO C17 standard allows these variations.
912 @item
913 In @theglibc{}, reallocation fails if the resulting block
914 would exceed @code{PTRDIFF_MAX} in size, to avoid problems with programs
915 that subtract pointers or use signed indexes.  Other implementations may
916 succeed, leading to undefined behavior later.
918 @item
919 In @theglibc{}, if the new size is the same as the old, @code{realloc} and
920 @code{reallocarray} are guaranteed to change nothing and return the same
921 address that you gave.  However, POSIX and ISO C allow the functions
922 to relocate the object or fail in this situation.
923 @end itemize
925 @node Allocating Cleared Space
926 @subsubsection Allocating Cleared Space
928 The function @code{calloc} allocates memory and clears it to zero.  It
929 is declared in @file{stdlib.h}.
930 @pindex stdlib.h
932 @deftypefun {void *} calloc (size_t @var{count}, size_t @var{eltsize})
933 @standards{ISO, malloc.h}
934 @standards{ISO, stdlib.h}
935 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
936 @c Same caveats as malloc.
938 @c __libc_calloc @asulock @aculock @acsfd @acsmem
939 @c  *__malloc_hook dup unguarded
940 @c  memset dup ok
941 @c  arena_get @asulock @aculock @acsfd @acsmem
942 @c   arena_lock dup @asulock @aculock @acsfd @acsmem
943 @c  top dup ok
944 @c  chunksize dup ok
945 @c  heap_for_ptr dup ok
946 @c  _int_malloc dup @acsfd @acsmem
947 @c  arena_get_retry dup @asulock @aculock @acsfd @acsmem
948 @c  mutex_unlock dup @aculock
949 @c  mem2chunk dup ok
950 @c  chunk_is_mmapped dup ok
951 @c  MALLOC_ZERO ok
952 @c   memset dup ok
953 This function allocates a block long enough to contain a vector of
954 @var{count} elements, each of size @var{eltsize}.  Its contents are
955 cleared to zero before @code{calloc} returns.
956 @end deftypefun
958 You could define @code{calloc} as follows:
960 @smallexample
961 void *
962 calloc (size_t count, size_t eltsize)
964   void *value = reallocarray (0, count, eltsize);
965   if (value != 0)
966     memset (value, 0, count * eltsize);
967   return value;
969 @end smallexample
971 But in general, it is not guaranteed that @code{calloc} calls
972 @code{reallocarray} and @code{memset} internally.  For example, if the
973 @code{calloc} implementation knows for other reasons that the new
974 memory block is zero, it need not zero out the block again with
975 @code{memset}.  Also, if an application provides its own
976 @code{reallocarray} outside the C library, @code{calloc} might not use
977 that redefinition.  @xref{Replacing malloc}.
979 @node Aligned Memory Blocks
980 @subsubsection Allocating Aligned Memory Blocks
982 @cindex page boundary
983 @cindex alignment (with @code{malloc})
984 @pindex stdlib.h
985 The address of a block returned by @code{malloc} or @code{realloc} in
986 @gnusystems{} is always a multiple of eight (or sixteen on 64-bit
987 systems).  If you need a block whose address is a multiple of a higher
988 power of two than that, use @code{aligned_alloc} or @code{posix_memalign}.
989 @code{aligned_alloc} and @code{posix_memalign} are declared in
990 @file{stdlib.h}.
992 @deftypefun {void *} aligned_alloc (size_t @var{alignment}, size_t @var{size})
993 @standards{???, stdlib.h}
994 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
995 @c Alias to memalign.
996 The @code{aligned_alloc} function allocates a block of @var{size} bytes whose
997 address is a multiple of @var{alignment}.  The @var{alignment} must be a
998 power of two.
1000 The @code{aligned_alloc} function returns a null pointer on error and sets
1001 @code{errno} to one of the following values:
1003 @table @code
1004 @item ENOMEM
1005 There was insufficient memory available to satisfy the request.
1007 @item EINVAL
1008 @var{alignment} is not a power of two.
1010 This function was introduced in @w{ISO C11} and hence may have better
1011 portability to modern non-POSIX systems than @code{posix_memalign}.
1012 @end table
1014 @end deftypefun
1016 @deftypefun {void *} memalign (size_t @var{boundary}, size_t @var{size})
1017 @standards{BSD, malloc.h}
1018 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
1019 @c Same issues as malloc.  The padding bytes are safely freed in
1020 @c _int_memalign, with the arena still locked.
1022 @c __libc_memalign @asulock @aculock @acsfd @acsmem
1023 @c  *__memalign_hook dup unguarded
1024 @c  __libc_malloc dup @asulock @aculock @acsfd @acsmem
1025 @c  arena_get dup @asulock @aculock @acsfd @acsmem
1026 @c  _int_memalign @acsfd @acsmem
1027 @c   _int_malloc dup @acsfd @acsmem
1028 @c   checked_request2size dup ok
1029 @c   mem2chunk dup ok
1030 @c   chunksize dup ok
1031 @c   chunk_is_mmapped dup ok
1032 @c   set_head dup ok
1033 @c   chunk2mem dup ok
1034 @c   set_inuse_bit_at_offset dup ok
1035 @c   set_head_size dup ok
1036 @c   _int_free (have_lock) dup @acsfd @acsmem
1037 @c   chunk_at_offset dup ok
1038 @c   check_inuse_chunk dup ok
1039 @c  arena_get_retry dup @asulock @aculock @acsfd @acsmem
1040 @c  mutex_unlock dup @aculock
1041 The @code{memalign} function allocates a block of @var{size} bytes whose
1042 address is a multiple of @var{boundary}.  The @var{boundary} must be a
1043 power of two!  The function @code{memalign} works by allocating a
1044 somewhat larger block, and then returning an address within the block
1045 that is on the specified boundary.
1047 The @code{memalign} function returns a null pointer on error and sets
1048 @code{errno} to one of the following values:
1050 @table @code
1051 @item ENOMEM
1052 There was insufficient memory available to satisfy the request.
1054 @item EINVAL
1055 @var{boundary} is not a power of two.
1057 @end table
1059 The @code{memalign} function is obsolete and @code{aligned_alloc} or
1060 @code{posix_memalign} should be used instead.
1061 @end deftypefun
1063 @deftypefun int posix_memalign (void **@var{memptr}, size_t @var{alignment}, size_t @var{size})
1064 @standards{POSIX, stdlib.h}
1065 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
1066 @c Calls memalign unless the requirements are not met (powerof2 macro is
1067 @c safe given an automatic variable as an argument) or there's a
1068 @c memalign hook (accessed unguarded, but safely).
1069 The @code{posix_memalign} function is similar to the @code{memalign}
1070 function in that it returns a buffer of @var{size} bytes aligned to a
1071 multiple of @var{alignment}.  But it adds one requirement to the
1072 parameter @var{alignment}: the value must be a power of two multiple of
1073 @code{sizeof (void *)}.
1075 If the function succeeds in allocation memory a pointer to the allocated
1076 memory is returned in @code{*@var{memptr}} and the return value is zero.
1077 Otherwise the function returns an error value indicating the problem.
1078 The possible error values returned are:
1080 @table @code
1081 @item ENOMEM
1082 There was insufficient memory available to satisfy the request.
1084 @item EINVAL
1085 @var{alignment} is not a power of two multiple of @code{sizeof (void *)}.
1087 @end table
1089 This function was introduced in POSIX 1003.1d.  Although this function is
1090 superseded by @code{aligned_alloc}, it is more portable to older POSIX
1091 systems that do not support @w{ISO C11}.
1092 @end deftypefun
1094 @deftypefun {void *} valloc (size_t @var{size})
1095 @standards{BSD, malloc.h}
1096 @standards{BSD, stdlib.h}
1097 @safety{@prelim{}@mtunsafe{@mtuinit{}}@asunsafe{@asuinit{} @asulock{}}@acunsafe{@acuinit{} @aculock{} @acsfd{} @acsmem{}}}
1098 @c __libc_valloc @mtuinit @asuinit @asulock @aculock @acsfd @acsmem
1099 @c  ptmalloc_init (once) @mtsenv @asulock @aculock @acsfd @acsmem
1100 @c   _dl_addr @asucorrupt? @aculock
1101 @c    __rtld_lock_lock_recursive (dl_load_lock) @asucorrupt? @aculock
1102 @c    _dl_find_dso_for_object ok, iterates over dl_ns and its _ns_loaded objs
1103 @c      the ok above assumes no partial updates on dl_ns and _ns_loaded
1104 @c      that could confuse a _dl_addr call in a signal handler
1105 @c     _dl_addr_inside_object ok
1106 @c    determine_info ok
1107 @c    __rtld_lock_unlock_recursive (dl_load_lock) @aculock
1108 @c   *_environ @mtsenv
1109 @c   next_env_entry ok
1110 @c   strcspn dup ok
1111 @c   __libc_mallopt dup @mtasuconst:mallopt [setting mp_]
1112 @c   *__malloc_initialize_hook unguarded, ok
1113 @c  *__memalign_hook dup ok, unguarded
1114 @c  arena_get dup @asulock @aculock @acsfd @acsmem
1115 @c  _int_valloc @acsfd @acsmem
1116 @c   malloc_consolidate dup ok
1117 @c   _int_memalign dup @acsfd @acsmem
1118 @c  arena_get_retry dup @asulock @aculock @acsfd @acsmem
1119 @c  _int_memalign dup @acsfd @acsmem
1120 @c  mutex_unlock dup @aculock
1121 Using @code{valloc} is like using @code{memalign} and passing the page size
1122 as the value of the first argument.  It is implemented like this:
1124 @smallexample
1125 void *
1126 valloc (size_t size)
1128   return memalign (getpagesize (), size);
1130 @end smallexample
1132 @ref{Query Memory Parameters} for more information about the memory
1133 subsystem.
1135 The @code{valloc} function is obsolete and @code{aligned_alloc} or
1136 @code{posix_memalign} should be used instead.
1137 @end deftypefun
1139 @node Malloc Tunable Parameters
1140 @subsubsection Malloc Tunable Parameters
1142 You can adjust some parameters for dynamic memory allocation with the
1143 @code{mallopt} function.  This function is the general SVID/XPG
1144 interface, defined in @file{malloc.h}.
1145 @pindex malloc.h
1147 @deftypefun int mallopt (int @var{param}, int @var{value})
1148 @safety{@prelim{}@mtunsafe{@mtuinit{} @mtasuconst{:mallopt}}@asunsafe{@asuinit{} @asulock{}}@acunsafe{@acuinit{} @aculock{}}}
1149 @c __libc_mallopt @mtuinit @mtasuconst:mallopt @asuinit @asulock @aculock
1150 @c  ptmalloc_init (once) dup @mtsenv @asulock @aculock @acsfd @acsmem
1151 @c  mutex_lock (main_arena->mutex) @asulock @aculock
1152 @c  malloc_consolidate dup ok
1153 @c  set_max_fast ok
1154 @c  mutex_unlock dup @aculock
1156 When calling @code{mallopt}, the @var{param} argument specifies the
1157 parameter to be set, and @var{value} the new value to be set.  Possible
1158 choices for @var{param}, as defined in @file{malloc.h}, are:
1160 @vtable @code
1161 @item M_MMAP_MAX
1162 The maximum number of chunks to allocate with @code{mmap}.  Setting this
1163 to zero disables all use of @code{mmap}.
1165 The default value of this parameter is @code{65536}.
1167 This parameter can also be set for the process at startup by setting the
1168 environment variable @env{MALLOC_MMAP_MAX_} to the desired value.
1170 @item M_MMAP_THRESHOLD
1171 All chunks larger than this value are allocated outside the normal
1172 heap, using the @code{mmap} system call.  This way it is guaranteed
1173 that the memory for these chunks can be returned to the system on
1174 @code{free}.  Note that requests smaller than this threshold might still
1175 be allocated via @code{mmap}.
1177 If this parameter is not set, the default value is set as 128 KiB and the
1178 threshold is adjusted dynamically to suit the allocation patterns of the
1179 program. If the parameter is set, the dynamic adjustment is disabled and the
1180 value is set statically to the input value.
1182 This parameter can also be set for the process at startup by setting the
1183 environment variable @env{MALLOC_MMAP_THRESHOLD_} to the desired value.
1184 @comment TODO: @item M_MXFAST
1186 @item M_PERTURB
1187 If non-zero, memory blocks are filled with values depending on some
1188 low order bits of this parameter when they are allocated (except when
1189 allocated by @code{calloc}) and freed.  This can be used to debug the
1190 use of uninitialized or freed heap memory.  Note that this option does not
1191 guarantee that the freed block will have any specific values.  It only
1192 guarantees that the content the block had before it was freed will be
1193 overwritten.
1195 The default value of this parameter is @code{0}.
1197 This parameter can also be set for the process at startup by setting the
1198 environment variable @env{MALLOC_PERTURB_} to the desired value.
1200 @item M_TOP_PAD
1201 This parameter determines the amount of extra memory to obtain from the system
1202 when an arena needs to be extended.  It also specifies the number of bytes to
1203 retain when shrinking an arena.  This provides the necessary hysteresis in heap
1204 size such that excessive amounts of system calls can be avoided.
1206 The default value of this parameter is @code{0}.
1208 This parameter can also be set for the process at startup by setting the
1209 environment variable @env{MALLOC_TOP_PAD_} to the desired value.
1211 @item M_TRIM_THRESHOLD
1212 This is the minimum size (in bytes) of the top-most, releasable chunk
1213 that will trigger a system call in order to return memory to the system.
1215 If this parameter is not set, the default value is set as 128 KiB and the
1216 threshold is adjusted dynamically to suit the allocation patterns of the
1217 program. If the parameter is set, the dynamic adjustment is disabled and the
1218 value is set statically to the provided input.
1220 This parameter can also be set for the process at startup by setting the
1221 environment variable @env{MALLOC_TRIM_THRESHOLD_} to the desired value.
1223 @item M_ARENA_TEST
1224 This parameter specifies the number of arenas that can be created before the
1225 test on the limit to the number of arenas is conducted. The value is ignored if
1226 @code{M_ARENA_MAX} is set.
1228 The default value of this parameter is 2 on 32-bit systems and 8 on 64-bit
1229 systems.
1231 This parameter can also be set for the process at startup by setting the
1232 environment variable @env{MALLOC_ARENA_TEST} to the desired value.
1234 @item M_ARENA_MAX
1235 This parameter sets the number of arenas to use regardless of the number of
1236 cores in the system.
1238 The default value of this tunable is @code{0}, meaning that the limit on the
1239 number of arenas is determined by the number of CPU cores online. For 32-bit
1240 systems the limit is twice the number of cores online and on 64-bit systems, it
1241 is eight times the number of cores online.  Note that the default value is not
1242 derived from the default value of M_ARENA_TEST and is computed independently.
1244 This parameter can also be set for the process at startup by setting the
1245 environment variable @env{MALLOC_ARENA_MAX} to the desired value.
1246 @end vtable
1248 @end deftypefun
1250 @node Heap Consistency Checking
1251 @subsubsection Heap Consistency Checking
1253 @cindex heap consistency checking
1254 @cindex consistency checking, of heap
1256 You can ask @code{malloc} to check the consistency of dynamic memory by
1257 using the @code{mcheck} function and preloading the malloc debug library
1258 @file{libc_malloc_debug} using the @var{LD_PRELOAD} environment variable.
1259 This function is a GNU extension, declared in @file{mcheck.h}.
1260 @pindex mcheck.h
1262 @deftypefun int mcheck (void (*@var{abortfn}) (enum mcheck_status @var{status}))
1263 @standards{GNU, mcheck.h}
1264 @safety{@prelim{}@mtunsafe{@mtasurace{:mcheck} @mtasuconst{:malloc_hooks}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
1265 @c The hooks must be set up before malloc is first used, which sort of
1266 @c implies @mtuinit/@asuinit but since the function is a no-op if malloc
1267 @c was already used, that doesn't pose any safety issues.  The actual
1268 @c problem is with the hooks, designed for single-threaded
1269 @c fully-synchronous operation: they manage an unguarded linked list of
1270 @c allocated blocks, and get temporarily overwritten before calling the
1271 @c allocation functions recursively while holding the old hooks.  There
1272 @c are no guards for thread safety, and inconsistent hooks may be found
1273 @c within signal handlers or left behind in case of cancellation.
1275 Calling @code{mcheck} tells @code{malloc} to perform occasional
1276 consistency checks.  These will catch things such as writing
1277 past the end of a block that was allocated with @code{malloc}.
1279 The @var{abortfn} argument is the function to call when an inconsistency
1280 is found.  If you supply a null pointer, then @code{mcheck} uses a
1281 default function which prints a message and calls @code{abort}
1282 (@pxref{Aborting a Program}).  The function you supply is called with
1283 one argument, which says what sort of inconsistency was detected; its
1284 type is described below.
1286 It is too late to begin allocation checking once you have allocated
1287 anything with @code{malloc}.  So @code{mcheck} does nothing in that
1288 case.  The function returns @code{-1} if you call it too late, and
1289 @code{0} otherwise (when it is successful).
1291 The easiest way to arrange to call @code{mcheck} early enough is to use
1292 the option @samp{-lmcheck} when you link your program; then you don't
1293 need to modify your program source at all.  Alternatively you might use
1294 a debugger to insert a call to @code{mcheck} whenever the program is
1295 started, for example these gdb commands will automatically call @code{mcheck}
1296 whenever the program starts:
1298 @smallexample
1299 (gdb) break main
1300 Breakpoint 1, main (argc=2, argv=0xbffff964) at whatever.c:10
1301 (gdb) command 1
1302 Type commands for when breakpoint 1 is hit, one per line.
1303 End with a line saying just "end".
1304 >call mcheck(0)
1305 >continue
1306 >end
1307 (gdb) @dots{}
1308 @end smallexample
1310 This will however only work if no initialization function of any object
1311 involved calls any of the @code{malloc} functions since @code{mcheck}
1312 must be called before the first such function.
1314 @end deftypefun
1316 @deftypefun {enum mcheck_status} mprobe (void *@var{pointer})
1317 @safety{@prelim{}@mtunsafe{@mtasurace{:mcheck} @mtasuconst{:malloc_hooks}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
1318 @c The linked list of headers may be modified concurrently by other
1319 @c threads, and it may find a partial update if called from a signal
1320 @c handler.  It's mostly read only, so cancelling it might be safe, but
1321 @c it will modify global state that, if cancellation hits at just the
1322 @c right spot, may be left behind inconsistent.  This path is only taken
1323 @c if checkhdr finds an inconsistency.  If the inconsistency could only
1324 @c occur because of earlier undefined behavior, that wouldn't be an
1325 @c additional safety issue problem, but because of the other concurrency
1326 @c issues in the mcheck hooks, the apparent inconsistency could be the
1327 @c result of mcheck's own internal data race.  So, AC-Unsafe it is.
1329 The @code{mprobe} function lets you explicitly check for inconsistencies
1330 in a particular allocated block.  You must have already called
1331 @code{mcheck} at the beginning of the program, to do its occasional
1332 checks; calling @code{mprobe} requests an additional consistency check
1333 to be done at the time of the call.
1335 The argument @var{pointer} must be a pointer returned by @code{malloc}
1336 or @code{realloc}.  @code{mprobe} returns a value that says what
1337 inconsistency, if any, was found.  The values are described below.
1338 @end deftypefun
1340 @deftp {Data Type} {enum mcheck_status}
1341 This enumerated type describes what kind of inconsistency was detected
1342 in an allocated block, if any.  Here are the possible values:
1344 @table @code
1345 @item MCHECK_DISABLED
1346 @code{mcheck} was not called before the first allocation.
1347 No consistency checking can be done.
1348 @item MCHECK_OK
1349 No inconsistency detected.
1350 @item MCHECK_HEAD
1351 The data immediately before the block was modified.
1352 This commonly happens when an array index or pointer
1353 is decremented too far.
1354 @item MCHECK_TAIL
1355 The data immediately after the block was modified.
1356 This commonly happens when an array index or pointer
1357 is incremented too far.
1358 @item MCHECK_FREE
1359 The block was already freed.
1360 @end table
1361 @end deftp
1363 Another possibility to check for and guard against bugs in the use of
1364 @code{malloc}, @code{realloc} and @code{free} is to set the environment
1365 variable @code{MALLOC_CHECK_}.  When @code{MALLOC_CHECK_} is set to a
1366 non-zero value less than 4, a special (less efficient) implementation is
1367 used which is designed to be tolerant against simple errors, such as
1368 double calls of @code{free} with the same argument, or overruns of a
1369 single byte (off-by-one bugs).  Not all such errors can be protected
1370 against, however, and memory leaks can result.  Like in the case of
1371 @code{mcheck}, one would need to preload the @file{libc_malloc_debug}
1372 library to enable @code{MALLOC_CHECK_} functionality.  Without this
1373 preloaded library, setting @code{MALLOC_CHECK_} will have no effect.
1375 Any detected heap corruption results in immediate termination of the
1376 process.
1378 There is one problem with @code{MALLOC_CHECK_}: in SUID or SGID binaries
1379 it could possibly be exploited since diverging from the normal programs
1380 behavior it now writes something to the standard error descriptor.
1381 Therefore the use of @code{MALLOC_CHECK_} is disabled by default for
1382 SUID and SGID binaries.
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 @c __morecore, __after_morecore_hook are undocumented
1392 @c It's not clear whether to document them.
1394 @node Statistics of Malloc
1395 @subsubsection Statistics for Memory Allocation with @code{malloc}
1397 @cindex allocation statistics
1398 You can get information about dynamic memory allocation by calling the
1399 @code{mallinfo2} function.  This function and its associated data type
1400 are declared in @file{malloc.h}; they are an extension of the standard
1401 SVID/XPG version.
1402 @pindex malloc.h
1404 @deftp {Data Type} {struct mallinfo2}
1405 @standards{GNU, malloc.h}
1406 This structure type is used to return information about the dynamic
1407 memory allocator.  It contains the following members:
1409 @table @code
1410 @item size_t arena
1411 This is the total size of memory allocated with @code{sbrk} by
1412 @code{malloc}, in bytes.
1414 @item size_t ordblks
1415 This is the number of chunks not in use.  (The memory allocator
1416 size_ternally gets chunks of memory from the operating system, and then
1417 carves them up to satisfy individual @code{malloc} requests;
1418 @pxref{The GNU Allocator}.)
1420 @item size_t smblks
1421 This field is unused.
1423 @item size_t hblks
1424 This is the total number of chunks allocated with @code{mmap}.
1426 @item size_t hblkhd
1427 This is the total size of memory allocated with @code{mmap}, in bytes.
1429 @item size_t usmblks
1430 This field is unused and always 0.
1432 @item size_t fsmblks
1433 This field is unused.
1435 @item size_t uordblks
1436 This is the total size of memory occupied by chunks handed out by
1437 @code{malloc}.
1439 @item size_t fordblks
1440 This is the total size of memory occupied by free (not in use) chunks.
1442 @item size_t keepcost
1443 This is the size of the top-most releasable chunk that normally
1444 borders the end of the heap (i.e., the high end of the virtual address
1445 space's data segment).
1447 @end table
1448 @end deftp
1450 @deftypefun {struct mallinfo2} mallinfo2 (void)
1451 @standards{SVID, malloc.h}
1452 @safety{@prelim{}@mtunsafe{@mtuinit{} @mtasuconst{:mallopt}}@asunsafe{@asuinit{} @asulock{}}@acunsafe{@acuinit{} @aculock{}}}
1453 @c Accessing mp_.n_mmaps and mp_.max_mmapped_mem, modified with atomics
1454 @c but non-atomically elsewhere, may get us inconsistent results.  We
1455 @c mark the statistics as unsafe, rather than the fast-path functions
1456 @c that collect the possibly inconsistent data.
1458 @c __libc_mallinfo2 @mtuinit @mtasuconst:mallopt @asuinit @asulock @aculock
1459 @c  ptmalloc_init (once) dup @mtsenv @asulock @aculock @acsfd @acsmem
1460 @c  mutex_lock dup @asulock @aculock
1461 @c  int_mallinfo @mtasuconst:mallopt [mp_ access on main_arena]
1462 @c   malloc_consolidate dup ok
1463 @c   check_malloc_state dup ok/disabled
1464 @c   chunksize dup ok
1465 @c   fastbin dupo ok
1466 @c   bin_at dup ok
1467 @c   last dup ok
1468 @c  mutex_unlock @aculock
1470 This function returns information about the current dynamic memory usage
1471 in a structure of type @code{struct mallinfo2}.
1472 @end deftypefun
1474 @node Summary of Malloc
1475 @subsubsection Summary of @code{malloc}-Related Functions
1477 Here is a summary of the functions that work with @code{malloc}:
1479 @table @code
1480 @item void *malloc (size_t @var{size})
1481 Allocate a block of @var{size} bytes.  @xref{Basic Allocation}.
1483 @item void free (void *@var{addr})
1484 Free a block previously allocated by @code{malloc}.  @xref{Freeing after
1485 Malloc}.
1487 @item void *realloc (void *@var{addr}, size_t @var{size})
1488 Make a block previously allocated by @code{malloc} larger or smaller,
1489 possibly by copying it to a new location.  @xref{Changing Block Size}.
1491 @item void *reallocarray (void *@var{ptr}, size_t @var{nmemb}, size_t @var{size})
1492 Change the size of a block previously allocated by @code{malloc} to
1493 @code{@var{nmemb} * @var{size}} bytes as with @code{realloc}.  @xref{Changing
1494 Block Size}.
1496 @item void *calloc (size_t @var{count}, size_t @var{eltsize})
1497 Allocate a block of @var{count} * @var{eltsize} bytes using
1498 @code{malloc}, and set its contents to zero.  @xref{Allocating Cleared
1499 Space}.
1501 @item void *valloc (size_t @var{size})
1502 Allocate a block of @var{size} bytes, starting on a page boundary.
1503 @xref{Aligned Memory Blocks}.
1505 @item void *aligned_alloc (size_t @var{alignment}, size_t @var{size})
1506 Allocate a block of @var{size} bytes, starting on an address that is a
1507 multiple of @var{alignment}.  @xref{Aligned Memory Blocks}.
1509 @item int posix_memalign (void **@var{memptr}, size_t @var{alignment}, size_t @var{size})
1510 Allocate a block of @var{size} bytes, starting on an address that is a
1511 multiple of @var{alignment}.  @xref{Aligned Memory Blocks}.
1513 @item void *memalign (size_t @var{boundary}, size_t @var{size})
1514 Allocate a block of @var{size} bytes, starting on an address that is a
1515 multiple of @var{boundary}.  @xref{Aligned Memory Blocks}.
1517 @item int mallopt (int @var{param}, int @var{value})
1518 Adjust a tunable parameter.  @xref{Malloc Tunable Parameters}.
1520 @item int mcheck (void (*@var{abortfn}) (void))
1521 Tell @code{malloc} to perform occasional consistency checks on
1522 dynamically allocated memory, and to call @var{abortfn} when an
1523 inconsistency is found.  @xref{Heap Consistency Checking}.
1525 @item struct mallinfo2 mallinfo2 (void)
1526 Return information about the current dynamic memory usage.
1527 @xref{Statistics of Malloc}.
1528 @end table
1530 @node Allocation Debugging
1531 @subsection Allocation Debugging
1532 @cindex allocation debugging
1533 @cindex malloc debugger
1535 A complicated task when programming with languages which do not use
1536 garbage collected dynamic memory allocation is to find memory leaks.
1537 Long running programs must ensure that dynamically allocated objects are
1538 freed at the end of their lifetime.  If this does not happen the system
1539 runs out of memory, sooner or later.
1541 The @code{malloc} implementation in @theglibc{} provides some
1542 simple means to detect such leaks and obtain some information to find
1543 the location.  To do this the application must be started in a special
1544 mode which is enabled by an environment variable.  There are no speed
1545 penalties for the program if the debugging mode is not enabled.
1547 @menu
1548 * Tracing malloc::               How to install the tracing functionality.
1549 * Using the Memory Debugger::    Example programs excerpts.
1550 * Tips for the Memory Debugger:: Some more or less clever ideas.
1551 * Interpreting the traces::      What do all these lines mean?
1552 @end menu
1554 @node Tracing malloc
1555 @subsubsection How to install the tracing functionality
1557 @deftypefun void mtrace (void)
1558 @standards{GNU, mcheck.h}
1559 @safety{@prelim{}@mtunsafe{@mtsenv{} @mtasurace{:mtrace} @mtuinit{}}@asunsafe{@asuinit{} @ascuheap{} @asucorrupt{} @asulock{}}@acunsafe{@acuinit{} @acucorrupt{} @aculock{} @acsfd{} @acsmem{}}}
1560 @c Like the mcheck hooks, these are not designed with thread safety in
1561 @c mind, because the hook pointers are temporarily modified without
1562 @c regard to other threads, signals or cancellation.
1564 @c mtrace @mtuinit @mtasurace:mtrace @mtsenv @asuinit @ascuheap @asucorrupt @acuinit @acucorrupt @aculock @acsfd @acsmem
1565 @c  __libc_secure_getenv dup @mtsenv
1566 @c  malloc dup @ascuheap @acsmem
1567 @c  fopen dup @ascuheap @asulock @aculock @acsmem @acsfd
1568 @c  fcntl dup ok
1569 @c  setvbuf dup @aculock
1570 @c  fprintf dup (on newly-created stream) @aculock
1571 @c  __cxa_atexit (once) dup @asulock @aculock @acsmem
1572 @c  free dup @ascuheap @acsmem
1573 The @code{mtrace} function provides a way to trace memory allocation
1574 events in the program that calls it.  It is disabled by default in the
1575 library and can be enabled by preloading the debugging library
1576 @file{libc_malloc_debug} using the @code{LD_PRELOAD} environment
1577 variable.
1579 When the @code{mtrace} function is called it looks for an environment
1580 variable named @code{MALLOC_TRACE}.  This variable is supposed to
1581 contain a valid file name.  The user must have write access.  If the
1582 file already exists it is truncated.  If the environment variable is not
1583 set or it does not name a valid file which can be opened for writing
1584 nothing is done.  The behavior of @code{malloc} etc. is not changed.
1585 For obvious reasons this also happens if the application is installed
1586 with the SUID or SGID bit set.
1588 If the named file is successfully opened, @code{mtrace} installs special
1589 handlers for the functions @code{malloc}, @code{realloc}, and
1590 @code{free}.  From then on, all uses of these functions are traced and
1591 protocolled into the file.  There is now of course a speed penalty for all
1592 calls to the traced functions so tracing should not be enabled during normal
1593 use.
1595 This function is a GNU extension and generally not available on other
1596 systems.  The prototype can be found in @file{mcheck.h}.
1597 @end deftypefun
1599 @deftypefun void muntrace (void)
1600 @standards{GNU, mcheck.h}
1601 @safety{@prelim{}@mtunsafe{@mtasurace{:mtrace} @mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acucorrupt{} @acsmem{} @aculock{} @acsfd{}}}
1603 @c muntrace @mtasurace:mtrace @mtslocale @asucorrupt @ascuheap @acucorrupt @acsmem @aculock @acsfd
1604 @c  fprintf (fputs) dup @mtslocale @asucorrupt @ascuheap @acsmem @aculock @acucorrupt
1605 @c  fclose dup @ascuheap @asulock @aculock @acsmem @acsfd
1606 The @code{muntrace} function can be called after @code{mtrace} was used
1607 to enable tracing the @code{malloc} calls.  If no (successful) call of
1608 @code{mtrace} was made @code{muntrace} does nothing.
1610 Otherwise it deinstalls the handlers for @code{malloc}, @code{realloc},
1611 and @code{free} and then closes the protocol file.  No calls are
1612 protocolled anymore and the program runs again at full speed.
1614 This function is a GNU extension and generally not available on other
1615 systems.  The prototype can be found in @file{mcheck.h}.
1616 @end deftypefun
1618 @node Using the Memory Debugger
1619 @subsubsection Example program excerpts
1621 Even though the tracing functionality does not influence the runtime
1622 behavior of the program it is not a good idea to call @code{mtrace} in
1623 all programs.  Just imagine that you debug a program using @code{mtrace}
1624 and all other programs used in the debugging session also trace their
1625 @code{malloc} calls.  The output file would be the same for all programs
1626 and thus is unusable.  Therefore one should call @code{mtrace} only if
1627 compiled for debugging.  A program could therefore start like this:
1629 @example
1630 #include <mcheck.h>
1633 main (int argc, char *argv[])
1635 #ifdef DEBUGGING
1636   mtrace ();
1637 #endif
1638   @dots{}
1640 @end example
1642 This is all that is needed if you want to trace the calls during the
1643 whole runtime of the program.  Alternatively you can stop the tracing at
1644 any time with a call to @code{muntrace}.  It is even possible to restart
1645 the tracing again with a new call to @code{mtrace}.  But this can cause
1646 unreliable results since there may be calls of the functions which are
1647 not called.  Please note that not only the application uses the traced
1648 functions, also libraries (including the C library itself) use these
1649 functions.
1651 This last point is also why it is not a good idea to call @code{muntrace}
1652 before the program terminates.  The libraries are informed about the
1653 termination of the program only after the program returns from
1654 @code{main} or calls @code{exit} and so cannot free the memory they use
1655 before this time.
1657 So the best thing one can do is to call @code{mtrace} as the very first
1658 function in the program and never call @code{muntrace}.  So the program
1659 traces almost all uses of the @code{malloc} functions (except those
1660 calls which are executed by constructors of the program or used
1661 libraries).
1663 @node Tips for the Memory Debugger
1664 @subsubsection Some more or less clever ideas
1666 You know the situation.  The program is prepared for debugging and in
1667 all debugging sessions it runs well.  But once it is started without
1668 debugging the error shows up.  A typical example is a memory leak that
1669 becomes visible only when we turn off the debugging.  If you foresee
1670 such situations you can still win.  Simply use something equivalent to
1671 the following little program:
1673 @example
1674 #include <mcheck.h>
1675 #include <signal.h>
1677 static void
1678 enable (int sig)
1680   mtrace ();
1681   signal (SIGUSR1, enable);
1684 static void
1685 disable (int sig)
1687   muntrace ();
1688   signal (SIGUSR2, disable);
1692 main (int argc, char *argv[])
1694   @dots{}
1696   signal (SIGUSR1, enable);
1697   signal (SIGUSR2, disable);
1699   @dots{}
1701 @end example
1703 I.e., the user can start the memory debugger any time s/he wants if the
1704 program was started with @code{MALLOC_TRACE} set in the environment.
1705 The output will of course not show the allocations which happened before
1706 the first signal but if there is a memory leak this will show up
1707 nevertheless.
1709 @node Interpreting the traces
1710 @subsubsection Interpreting the traces
1712 If you take a look at the output it will look similar to this:
1714 @example
1715 = Start
1716 @ [0x8048209] - 0x8064cc8
1717 @ [0x8048209] - 0x8064ce0
1718 @ [0x8048209] - 0x8064cf8
1719 @ [0x80481eb] + 0x8064c48 0x14
1720 @ [0x80481eb] + 0x8064c60 0x14
1721 @ [0x80481eb] + 0x8064c78 0x14
1722 @ [0x80481eb] + 0x8064c90 0x14
1723 = End
1724 @end example
1726 What this all means is not really important since the trace file is not
1727 meant to be read by a human.  Therefore no attention is given to
1728 readability.  Instead there is a program which comes with @theglibc{}
1729 which interprets the traces and outputs a summary in an
1730 user-friendly way.  The program is called @code{mtrace} (it is in fact a
1731 Perl script) and it takes one or two arguments.  In any case the name of
1732 the file with the trace output must be specified.  If an optional
1733 argument precedes the name of the trace file this must be the name of
1734 the program which generated the trace.
1736 @example
1737 drepper$ mtrace tst-mtrace log
1738 No memory leaks.
1739 @end example
1741 In this case the program @code{tst-mtrace} was run and it produced a
1742 trace file @file{log}.  The message printed by @code{mtrace} shows there
1743 are no problems with the code, all allocated memory was freed
1744 afterwards.
1746 If we call @code{mtrace} on the example trace given above we would get a
1747 different output:
1749 @example
1750 drepper$ mtrace errlog
1751 - 0x08064cc8 Free 2 was never alloc'd 0x8048209
1752 - 0x08064ce0 Free 3 was never alloc'd 0x8048209
1753 - 0x08064cf8 Free 4 was never alloc'd 0x8048209
1755 Memory not freed:
1756 -----------------
1757    Address     Size     Caller
1758 0x08064c48     0x14  at 0x80481eb
1759 0x08064c60     0x14  at 0x80481eb
1760 0x08064c78     0x14  at 0x80481eb
1761 0x08064c90     0x14  at 0x80481eb
1762 @end example
1764 We have called @code{mtrace} with only one argument and so the script
1765 has no chance to find out what is meant with the addresses given in the
1766 trace.  We can do better:
1768 @example
1769 drepper$ mtrace tst errlog
1770 - 0x08064cc8 Free 2 was never alloc'd /home/drepper/tst.c:39
1771 - 0x08064ce0 Free 3 was never alloc'd /home/drepper/tst.c:39
1772 - 0x08064cf8 Free 4 was never alloc'd /home/drepper/tst.c:39
1774 Memory not freed:
1775 -----------------
1776    Address     Size     Caller
1777 0x08064c48     0x14  at /home/drepper/tst.c:33
1778 0x08064c60     0x14  at /home/drepper/tst.c:33
1779 0x08064c78     0x14  at /home/drepper/tst.c:33
1780 0x08064c90     0x14  at /home/drepper/tst.c:33
1781 @end example
1783 Suddenly the output makes much more sense and the user can see
1784 immediately where the function calls causing the trouble can be found.
1786 Interpreting this output is not complicated.  There are at most two
1787 different situations being detected.  First, @code{free} was called for
1788 pointers which were never returned by one of the allocation functions.
1789 This is usually a very bad problem and what this looks like is shown in
1790 the first three lines of the output.  Situations like this are quite
1791 rare and if they appear they show up very drastically: the program
1792 normally crashes.
1794 The other situation which is much harder to detect are memory leaks.  As
1795 you can see in the output the @code{mtrace} function collects all this
1796 information and so can say that the program calls an allocation function
1797 from line 33 in the source file @file{/home/drepper/tst-mtrace.c} four
1798 times without freeing this memory before the program terminates.
1799 Whether this is a real problem remains to be investigated.
1801 @node Replacing malloc
1802 @subsection Replacing @code{malloc}
1804 @cindex @code{malloc} replacement
1805 @cindex @code{LD_PRELOAD} and @code{malloc}
1806 @cindex alternative @code{malloc} implementations
1807 @cindex customizing @code{malloc}
1808 @cindex interposing @code{malloc}
1809 @cindex preempting @code{malloc}
1810 @cindex replacing @code{malloc}
1811 @Theglibc{} supports replacing the built-in @code{malloc} implementation
1812 with a different allocator with the same interface.  For dynamically
1813 linked programs, this happens through ELF symbol interposition, either
1814 using shared object dependencies or @code{LD_PRELOAD}.  For static
1815 linking, the @code{malloc} replacement library must be linked in before
1816 linking against @code{libc.a} (explicitly or implicitly).
1818 Care must be taken not to use functionality from @theglibc{} that uses
1819 @code{malloc} internally.  For example, the @code{fopen},
1820 @code{opendir}, @code{dlopen}, and @code{pthread_setspecific} functions
1821 currently use the @code{malloc} subsystem internally.  If the
1822 replacement @code{malloc} or its dependencies use thread-local storage
1823 (TLS), it must use the initial-exec TLS model, and not one of the
1824 dynamic TLS variants.
1826 @strong{Note:} Failure to provide a complete set of replacement
1827 functions (that is, all the functions used by the application,
1828 @theglibc{}, and other linked-in libraries) can lead to static linking
1829 failures, and, at run time, to heap corruption and application crashes.
1830 Replacement functions should implement the behavior documented for
1831 their counterparts in @theglibc{}; for example, the replacement
1832 @code{free} should also preserve @code{errno}.
1834 The minimum set of functions which has to be provided by a custom
1835 @code{malloc} is given in the table below.
1837 @table @code
1838 @item malloc
1839 @item free
1840 @item calloc
1841 @item realloc
1842 @end table
1844 These @code{malloc}-related functions are required for @theglibc{} to
1845 work.@footnote{Versions of @theglibc{} before 2.25 required that a
1846 custom @code{malloc} defines @code{__libc_memalign} (with the same
1847 interface as the @code{memalign} function).}
1849 The @code{malloc} implementation in @theglibc{} provides additional
1850 functionality not used by the library itself, but which is often used by
1851 other system libraries and applications.  A general-purpose replacement
1852 @code{malloc} implementation should provide definitions of these
1853 functions, too.  Their names are listed in the following table.
1855 @table @code
1856 @item aligned_alloc
1857 @item malloc_usable_size
1858 @item memalign
1859 @item posix_memalign
1860 @item pvalloc
1861 @item valloc
1862 @end table
1864 In addition, very old applications may use the obsolete @code{cfree}
1865 function.
1867 Further @code{malloc}-related functions such as @code{mallopt} or
1868 @code{mallinfo2} will not have any effect or return incorrect statistics
1869 when a replacement @code{malloc} is in use.  However, failure to replace
1870 these functions typically does not result in crashes or other incorrect
1871 application behavior, but may result in static linking failures.
1873 There are other functions (@code{reallocarray}, @code{strdup}, etc.) in
1874 @theglibc{} that are not listed above but return newly allocated memory to
1875 callers.  Replacement of these functions is not supported and may produce
1876 incorrect results.  @Theglibc{} implementations of these functions call
1877 the replacement allocator functions whenever available, so they will work
1878 correctly with @code{malloc} replacement.
1880 @node Obstacks
1881 @subsection Obstacks
1882 @cindex obstacks
1884 An @dfn{obstack} is a pool of memory containing a stack of objects.  You
1885 can create any number of separate obstacks, and then allocate objects in
1886 specified obstacks.  Within each obstack, the last object allocated must
1887 always be the first one freed, but distinct obstacks are independent of
1888 each other.
1890 Aside from this one constraint of order of freeing, obstacks are totally
1891 general: an obstack can contain any number of objects of any size.  They
1892 are implemented with macros, so allocation is usually very fast as long as
1893 the objects are usually small.  And the only space overhead per object is
1894 the padding needed to start each object on a suitable boundary.
1896 @menu
1897 * Creating Obstacks::           How to declare an obstack in your program.
1898 * Preparing for Obstacks::      Preparations needed before you can
1899                                  use obstacks.
1900 * Allocation in an Obstack::    Allocating objects in an obstack.
1901 * Freeing Obstack Objects::     Freeing objects in an obstack.
1902 * Obstack Functions::           The obstack functions are both
1903                                  functions and macros.
1904 * Growing Objects::             Making an object bigger by stages.
1905 * Extra Fast Growing::          Extra-high-efficiency (though more
1906                                  complicated) growing objects.
1907 * Status of an Obstack::        Inquiries about the status of an obstack.
1908 * Obstacks Data Alignment::     Controlling alignment of objects in obstacks.
1909 * Obstack Chunks::              How obstacks obtain and release chunks;
1910                                  efficiency considerations.
1911 * Summary of Obstacks::
1912 @end menu
1914 @node Creating Obstacks
1915 @subsubsection Creating Obstacks
1917 The utilities for manipulating obstacks are declared in the header
1918 file @file{obstack.h}.
1919 @pindex obstack.h
1921 @deftp {Data Type} {struct obstack}
1922 @standards{GNU, obstack.h}
1923 An obstack is represented by a data structure of type @code{struct
1924 obstack}.  This structure has a small fixed size; it records the status
1925 of the obstack and how to find the space in which objects are allocated.
1926 It does not contain any of the objects themselves.  You should not try
1927 to access the contents of the structure directly; use only the functions
1928 described in this chapter.
1929 @end deftp
1931 You can declare variables of type @code{struct obstack} and use them as
1932 obstacks, or you can allocate obstacks dynamically like any other kind
1933 of object.  Dynamic allocation of obstacks allows your program to have a
1934 variable number of different stacks.  (You can even allocate an
1935 obstack structure in another obstack, but this is rarely useful.)
1937 All the functions that work with obstacks require you to specify which
1938 obstack to use.  You do this with a pointer of type @code{struct obstack
1939 *}.  In the following, we often say ``an obstack'' when strictly
1940 speaking the object at hand is such a pointer.
1942 The objects in the obstack are packed into large blocks called
1943 @dfn{chunks}.  The @code{struct obstack} structure points to a chain of
1944 the chunks currently in use.
1946 The obstack library obtains a new chunk whenever you allocate an object
1947 that won't fit in the previous chunk.  Since the obstack library manages
1948 chunks automatically, you don't need to pay much attention to them, but
1949 you do need to supply a function which the obstack library should use to
1950 get a chunk.  Usually you supply a function which uses @code{malloc}
1951 directly or indirectly.  You must also supply a function to free a chunk.
1952 These matters are described in the following section.
1954 @node Preparing for Obstacks
1955 @subsubsection Preparing for Using Obstacks
1957 Each source file in which you plan to use the obstack functions
1958 must include the header file @file{obstack.h}, like this:
1960 @smallexample
1961 #include <obstack.h>
1962 @end smallexample
1964 @findex obstack_chunk_alloc
1965 @findex obstack_chunk_free
1966 Also, if the source file uses the macro @code{obstack_init}, it must
1967 declare or define two functions or macros that will be called by the
1968 obstack library.  One, @code{obstack_chunk_alloc}, is used to allocate
1969 the chunks of memory into which objects are packed.  The other,
1970 @code{obstack_chunk_free}, is used to return chunks when the objects in
1971 them are freed.  These macros should appear before any use of obstacks
1972 in the source file.
1974 Usually these are defined to use @code{malloc} via the intermediary
1975 @code{xmalloc} (@pxref{Unconstrained Allocation}).  This is done with
1976 the following pair of macro definitions:
1978 @smallexample
1979 #define obstack_chunk_alloc xmalloc
1980 #define obstack_chunk_free free
1981 @end smallexample
1983 @noindent
1984 Though the memory you get using obstacks really comes from @code{malloc},
1985 using obstacks is faster because @code{malloc} is called less often, for
1986 larger blocks of memory.  @xref{Obstack Chunks}, for full details.
1988 At run time, before the program can use a @code{struct obstack} object
1989 as an obstack, it must initialize the obstack by calling
1990 @code{obstack_init}.
1992 @deftypefun int obstack_init (struct obstack *@var{obstack-ptr})
1993 @standards{GNU, obstack.h}
1994 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{@acsmem{}}}
1995 @c obstack_init @mtsrace:obstack-ptr @acsmem
1996 @c  _obstack_begin @acsmem
1997 @c    chunkfun = obstack_chunk_alloc (suggested malloc)
1998 @c    freefun = obstack_chunk_free (suggested free)
1999 @c   *chunkfun @acsmem
2000 @c    obstack_chunk_alloc user-supplied
2001 @c   *obstack_alloc_failed_handler user-supplied
2002 @c    -> print_and_abort (default)
2004 @c print_and_abort
2005 @c  _ dup @ascuintl
2006 @c  fxprintf dup @asucorrupt @aculock @acucorrupt
2007 @c  exit @acucorrupt?
2008 Initialize obstack @var{obstack-ptr} for allocation of objects.  This
2009 function calls the obstack's @code{obstack_chunk_alloc} function.  If
2010 allocation of memory fails, the function pointed to by
2011 @code{obstack_alloc_failed_handler} is called.  The @code{obstack_init}
2012 function always returns 1 (Compatibility notice: Former versions of
2013 obstack returned 0 if allocation failed).
2014 @end deftypefun
2016 Here are two examples of how to allocate the space for an obstack and
2017 initialize it.  First, an obstack that is a static variable:
2019 @smallexample
2020 static struct obstack myobstack;
2021 @dots{}
2022 obstack_init (&myobstack);
2023 @end smallexample
2025 @noindent
2026 Second, an obstack that is itself dynamically allocated:
2028 @smallexample
2029 struct obstack *myobstack_ptr
2030   = (struct obstack *) xmalloc (sizeof (struct obstack));
2032 obstack_init (myobstack_ptr);
2033 @end smallexample
2035 @defvar obstack_alloc_failed_handler
2036 @standards{GNU, obstack.h}
2037 The value of this variable is a pointer to a function that
2038 @code{obstack} uses when @code{obstack_chunk_alloc} fails to allocate
2039 memory.  The default action is to print a message and abort.
2040 You should supply a function that either calls @code{exit}
2041 (@pxref{Program Termination}) or @code{longjmp} (@pxref{Non-Local
2042 Exits}) and doesn't return.
2044 @smallexample
2045 void my_obstack_alloc_failed (void)
2046 @dots{}
2047 obstack_alloc_failed_handler = &my_obstack_alloc_failed;
2048 @end smallexample
2050 @end defvar
2052 @node Allocation in an Obstack
2053 @subsubsection Allocation in an Obstack
2054 @cindex allocation (obstacks)
2056 The most direct way to allocate an object in an obstack is with
2057 @code{obstack_alloc}, which is invoked almost like @code{malloc}.
2059 @deftypefun {void *} obstack_alloc (struct obstack *@var{obstack-ptr}, int @var{size})
2060 @standards{GNU, obstack.h}
2061 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2062 @c obstack_alloc @mtsrace:obstack-ptr @acucorrupt @acsmem
2063 @c  obstack_blank dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2064 @c  obstack_finish dup @mtsrace:obstack-ptr @acucorrupt
2065 This allocates an uninitialized block of @var{size} bytes in an obstack
2066 and returns its address.  Here @var{obstack-ptr} specifies which obstack
2067 to allocate the block in; it is the address of the @code{struct obstack}
2068 object which represents the obstack.  Each obstack function or macro
2069 requires you to specify an @var{obstack-ptr} as the first argument.
2071 This function calls the obstack's @code{obstack_chunk_alloc} function if
2072 it needs to allocate a new chunk of memory; it calls
2073 @code{obstack_alloc_failed_handler} if allocation of memory by
2074 @code{obstack_chunk_alloc} failed.
2075 @end deftypefun
2077 For example, here is a function that allocates a copy of a string @var{str}
2078 in a specific obstack, which is in the variable @code{string_obstack}:
2080 @smallexample
2081 struct obstack string_obstack;
2083 char *
2084 copystring (char *string)
2086   size_t len = strlen (string) + 1;
2087   char *s = (char *) obstack_alloc (&string_obstack, len);
2088   memcpy (s, string, len);
2089   return s;
2091 @end smallexample
2093 To allocate a block with specified contents, use the function
2094 @code{obstack_copy}, declared like this:
2096 @deftypefun {void *} obstack_copy (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2097 @standards{GNU, obstack.h}
2098 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2099 @c obstack_copy @mtsrace:obstack-ptr @acucorrupt @acsmem
2100 @c  obstack_grow dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2101 @c  obstack_finish dup @mtsrace:obstack-ptr @acucorrupt
2102 This allocates a block and initializes it by copying @var{size}
2103 bytes of data starting at @var{address}.  It calls
2104 @code{obstack_alloc_failed_handler} if allocation of memory by
2105 @code{obstack_chunk_alloc} failed.
2106 @end deftypefun
2108 @deftypefun {void *} obstack_copy0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2109 @standards{GNU, obstack.h}
2110 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2111 @c obstack_copy0 @mtsrace:obstack-ptr @acucorrupt @acsmem
2112 @c  obstack_grow0 dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2113 @c  obstack_finish dup @mtsrace:obstack-ptr @acucorrupt
2114 Like @code{obstack_copy}, but appends an extra byte containing a null
2115 character.  This extra byte is not counted in the argument @var{size}.
2116 @end deftypefun
2118 The @code{obstack_copy0} function is convenient for copying a sequence
2119 of characters into an obstack as a null-terminated string.  Here is an
2120 example of its use:
2122 @smallexample
2123 char *
2124 obstack_savestring (char *addr, int size)
2126   return obstack_copy0 (&myobstack, addr, size);
2128 @end smallexample
2130 @noindent
2131 Contrast this with the previous example of @code{savestring} using
2132 @code{malloc} (@pxref{Basic Allocation}).
2134 @node Freeing Obstack Objects
2135 @subsubsection Freeing Objects in an Obstack
2136 @cindex freeing (obstacks)
2138 To free an object allocated in an obstack, use the function
2139 @code{obstack_free}.  Since the obstack is a stack of objects, freeing
2140 one object automatically frees all other objects allocated more recently
2141 in the same obstack.
2143 @deftypefun void obstack_free (struct obstack *@var{obstack-ptr}, void *@var{object})
2144 @standards{GNU, obstack.h}
2145 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{}}}
2146 @c obstack_free @mtsrace:obstack-ptr @acucorrupt
2147 @c  (obstack_free) @mtsrace:obstack-ptr @acucorrupt
2148 @c   *freefun dup user-supplied
2149 If @var{object} is a null pointer, everything allocated in the obstack
2150 is freed.  Otherwise, @var{object} must be the address of an object
2151 allocated in the obstack.  Then @var{object} is freed, along with
2152 everything allocated in @var{obstack-ptr} since @var{object}.
2153 @end deftypefun
2155 Note that if @var{object} is a null pointer, the result is an
2156 uninitialized obstack.  To free all memory in an obstack but leave it
2157 valid for further allocation, call @code{obstack_free} with the address
2158 of the first object allocated on the obstack:
2160 @smallexample
2161 obstack_free (obstack_ptr, first_object_allocated_ptr);
2162 @end smallexample
2164 Recall that the objects in an obstack are grouped into chunks.  When all
2165 the objects in a chunk become free, the obstack library automatically
2166 frees the chunk (@pxref{Preparing for Obstacks}).  Then other
2167 obstacks, or non-obstack allocation, can reuse the space of the chunk.
2169 @node Obstack Functions
2170 @subsubsection Obstack Functions and Macros
2171 @cindex macros
2173 The interfaces for using obstacks may be defined either as functions or
2174 as macros, depending on the compiler.  The obstack facility works with
2175 all C compilers, including both @w{ISO C} and traditional C, but there are
2176 precautions you must take if you plan to use compilers other than GNU C.
2178 If you are using an old-fashioned @w{non-ISO C} compiler, all the obstack
2179 ``functions'' are actually defined only as macros.  You can call these
2180 macros like functions, but you cannot use them in any other way (for
2181 example, you cannot take their address).
2183 Calling the macros requires a special precaution: namely, the first
2184 operand (the obstack pointer) may not contain any side effects, because
2185 it may be computed more than once.  For example, if you write this:
2187 @smallexample
2188 obstack_alloc (get_obstack (), 4);
2189 @end smallexample
2191 @noindent
2192 you will find that @code{get_obstack} may be called several times.
2193 If you use @code{*obstack_list_ptr++} as the obstack pointer argument,
2194 you will get very strange results since the incrementation may occur
2195 several times.
2197 In @w{ISO C}, each function has both a macro definition and a function
2198 definition.  The function definition is used if you take the address of the
2199 function without calling it.  An ordinary call uses the macro definition by
2200 default, but you can request the function definition instead by writing the
2201 function name in parentheses, as shown here:
2203 @smallexample
2204 char *x;
2205 void *(*funcp) ();
2206 /* @r{Use the macro}.  */
2207 x = (char *) obstack_alloc (obptr, size);
2208 /* @r{Call the function}.  */
2209 x = (char *) (obstack_alloc) (obptr, size);
2210 /* @r{Take the address of the function}.  */
2211 funcp = obstack_alloc;
2212 @end smallexample
2214 @noindent
2215 This is the same situation that exists in @w{ISO C} for the standard library
2216 functions.  @xref{Macro Definitions}.
2218 @strong{Warning:} When you do use the macros, you must observe the
2219 precaution of avoiding side effects in the first operand, even in @w{ISO C}.
2221 If you use the GNU C compiler, this precaution is not necessary, because
2222 various language extensions in GNU C permit defining the macros so as to
2223 compute each argument only once.
2225 @node Growing Objects
2226 @subsubsection Growing Objects
2227 @cindex growing objects (in obstacks)
2228 @cindex changing the size of a block (obstacks)
2230 Because memory in obstack chunks is used sequentially, it is possible to
2231 build up an object step by step, adding one or more bytes at a time to the
2232 end of the object.  With this technique, you do not need to know how much
2233 data you will put in the object until you come to the end of it.  We call
2234 this the technique of @dfn{growing objects}.  The special functions
2235 for adding data to the growing object are described in this section.
2237 You don't need to do anything special when you start to grow an object.
2238 Using one of the functions to add data to the object automatically
2239 starts it.  However, it is necessary to say explicitly when the object is
2240 finished.  This is done with the function @code{obstack_finish}.
2242 The actual address of the object thus built up is not known until the
2243 object is finished.  Until then, it always remains possible that you will
2244 add so much data that the object must be copied into a new chunk.
2246 While the obstack is in use for a growing object, you cannot use it for
2247 ordinary allocation of another object.  If you try to do so, the space
2248 already added to the growing object will become part of the other object.
2250 @deftypefun void obstack_blank (struct obstack *@var{obstack-ptr}, int @var{size})
2251 @standards{GNU, obstack.h}
2252 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2253 @c obstack_blank @mtsrace:obstack-ptr @acucorrupt @acsmem
2254 @c  _obstack_newchunk @mtsrace:obstack-ptr @acucorrupt @acsmem
2255 @c   *chunkfun dup @acsmem
2256 @c   *obstack_alloc_failed_handler dup user-supplied
2257 @c   *freefun
2258 @c  obstack_blank_fast dup @mtsrace:obstack-ptr
2259 The most basic function for adding to a growing object is
2260 @code{obstack_blank}, which adds space without initializing it.
2261 @end deftypefun
2263 @deftypefun void obstack_grow (struct obstack *@var{obstack-ptr}, void *@var{data}, int @var{size})
2264 @standards{GNU, obstack.h}
2265 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2266 @c obstack_grow @mtsrace:obstack-ptr @acucorrupt @acsmem
2267 @c  _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2268 @c  memcpy ok
2269 To add a block of initialized space, use @code{obstack_grow}, which is
2270 the growing-object analogue of @code{obstack_copy}.  It adds @var{size}
2271 bytes of data to the growing object, copying the contents from
2272 @var{data}.
2273 @end deftypefun
2275 @deftypefun void obstack_grow0 (struct obstack *@var{obstack-ptr}, void *@var{data}, int @var{size})
2276 @standards{GNU, obstack.h}
2277 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2278 @c obstack_grow0 @mtsrace:obstack-ptr @acucorrupt @acsmem
2279 @c   (no sequence point between storing NUL and incrementing next_free)
2280 @c   (multiple changes to next_free => @acucorrupt)
2281 @c  _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2282 @c  memcpy ok
2283 This is the growing-object analogue of @code{obstack_copy0}.  It adds
2284 @var{size} bytes copied from @var{data}, followed by an additional null
2285 character.
2286 @end deftypefun
2288 @deftypefun void obstack_1grow (struct obstack *@var{obstack-ptr}, char @var{c})
2289 @standards{GNU, obstack.h}
2290 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2291 @c obstack_1grow @mtsrace:obstack-ptr @acucorrupt @acsmem
2292 @c  _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2293 @c  obstack_1grow_fast dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2294 To add one character at a time, use the function @code{obstack_1grow}.
2295 It adds a single byte containing @var{c} to the growing object.
2296 @end deftypefun
2298 @deftypefun void obstack_ptr_grow (struct obstack *@var{obstack-ptr}, void *@var{data})
2299 @standards{GNU, obstack.h}
2300 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2301 @c obstack_ptr_grow @mtsrace:obstack-ptr @acucorrupt @acsmem
2302 @c  _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2303 @c  obstack_ptr_grow_fast dup @mtsrace:obstack-ptr
2304 Adding the value of a pointer one can use the function
2305 @code{obstack_ptr_grow}.  It adds @code{sizeof (void *)} bytes
2306 containing the value of @var{data}.
2307 @end deftypefun
2309 @deftypefun void obstack_int_grow (struct obstack *@var{obstack-ptr}, int @var{data})
2310 @standards{GNU, obstack.h}
2311 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2312 @c obstack_int_grow @mtsrace:obstack-ptr @acucorrupt @acsmem
2313 @c  _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2314 @c  obstack_int_grow_fast dup @mtsrace:obstack-ptr
2315 A single value of type @code{int} can be added by using the
2316 @code{obstack_int_grow} function.  It adds @code{sizeof (int)} bytes to
2317 the growing object and initializes them with the value of @var{data}.
2318 @end deftypefun
2320 @deftypefun {void *} obstack_finish (struct obstack *@var{obstack-ptr})
2321 @standards{GNU, obstack.h}
2322 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{}}}
2323 @c obstack_finish @mtsrace:obstack-ptr @acucorrupt
2324 When you are finished growing the object, use the function
2325 @code{obstack_finish} to close it off and return its final address.
2327 Once you have finished the object, the obstack is available for ordinary
2328 allocation or for growing another object.
2330 This function can return a null pointer under the same conditions as
2331 @code{obstack_alloc} (@pxref{Allocation in an Obstack}).
2332 @end deftypefun
2334 When you build an object by growing it, you will probably need to know
2335 afterward how long it became.  You need not keep track of this as you grow
2336 the object, because you can find out the length from the obstack just
2337 before finishing the object with the function @code{obstack_object_size},
2338 declared as follows:
2340 @deftypefun int obstack_object_size (struct obstack *@var{obstack-ptr})
2341 @standards{GNU, obstack.h}
2342 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
2343 This function returns the current size of the growing object, in bytes.
2344 Remember to call this function @emph{before} finishing the object.
2345 After it is finished, @code{obstack_object_size} will return zero.
2346 @end deftypefun
2348 If you have started growing an object and wish to cancel it, you should
2349 finish it and then free it, like this:
2351 @smallexample
2352 obstack_free (obstack_ptr, obstack_finish (obstack_ptr));
2353 @end smallexample
2355 @noindent
2356 This has no effect if no object was growing.
2358 @cindex shrinking objects
2359 You can use @code{obstack_blank} with a negative size argument to make
2360 the current object smaller.  Just don't try to shrink it beyond zero
2361 length---there's no telling what will happen if you do that.
2363 @node Extra Fast Growing
2364 @subsubsection Extra Fast Growing Objects
2365 @cindex efficiency and obstacks
2367 The usual functions for growing objects incur overhead for checking
2368 whether there is room for the new growth in the current chunk.  If you
2369 are frequently constructing objects in small steps of growth, this
2370 overhead can be significant.
2372 You can reduce the overhead by using special ``fast growth''
2373 functions that grow the object without checking.  In order to have a
2374 robust program, you must do the checking yourself.  If you do this checking
2375 in the simplest way each time you are about to add data to the object, you
2376 have not saved anything, because that is what the ordinary growth
2377 functions do.  But if you can arrange to check less often, or check
2378 more efficiently, then you make the program faster.
2380 The function @code{obstack_room} returns the amount of room available
2381 in the current chunk.  It is declared as follows:
2383 @deftypefun int obstack_room (struct obstack *@var{obstack-ptr})
2384 @standards{GNU, obstack.h}
2385 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
2386 This returns the number of bytes that can be added safely to the current
2387 growing object (or to an object about to be started) in obstack
2388 @var{obstack-ptr} using the fast growth functions.
2389 @end deftypefun
2391 While you know there is room, you can use these fast growth functions
2392 for adding data to a growing object:
2394 @deftypefun void obstack_1grow_fast (struct obstack *@var{obstack-ptr}, char @var{c})
2395 @standards{GNU, obstack.h}
2396 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2397 @c obstack_1grow_fast @mtsrace:obstack-ptr @acucorrupt @acsmem
2398 @c   (no sequence point between copying c and incrementing next_free)
2399 The function @code{obstack_1grow_fast} adds one byte containing the
2400 character @var{c} to the growing object in obstack @var{obstack-ptr}.
2401 @end deftypefun
2403 @deftypefun void obstack_ptr_grow_fast (struct obstack *@var{obstack-ptr}, void *@var{data})
2404 @standards{GNU, obstack.h}
2405 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
2406 @c obstack_ptr_grow_fast @mtsrace:obstack-ptr
2407 The function @code{obstack_ptr_grow_fast} adds @code{sizeof (void *)}
2408 bytes containing the value of @var{data} to the growing object in
2409 obstack @var{obstack-ptr}.
2410 @end deftypefun
2412 @deftypefun void obstack_int_grow_fast (struct obstack *@var{obstack-ptr}, int @var{data})
2413 @standards{GNU, obstack.h}
2414 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
2415 @c obstack_int_grow_fast @mtsrace:obstack-ptr
2416 The function @code{obstack_int_grow_fast} adds @code{sizeof (int)} bytes
2417 containing the value of @var{data} to the growing object in obstack
2418 @var{obstack-ptr}.
2419 @end deftypefun
2421 @deftypefun void obstack_blank_fast (struct obstack *@var{obstack-ptr}, int @var{size})
2422 @standards{GNU, obstack.h}
2423 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
2424 @c obstack_blank_fast @mtsrace:obstack-ptr
2425 The function @code{obstack_blank_fast} adds @var{size} bytes to the
2426 growing object in obstack @var{obstack-ptr} without initializing them.
2427 @end deftypefun
2429 When you check for space using @code{obstack_room} and there is not
2430 enough room for what you want to add, the fast growth functions
2431 are not safe.  In this case, simply use the corresponding ordinary
2432 growth function instead.  Very soon this will copy the object to a
2433 new chunk; then there will be lots of room available again.
2435 So, each time you use an ordinary growth function, check afterward for
2436 sufficient space using @code{obstack_room}.  Once the object is copied
2437 to a new chunk, there will be plenty of space again, so the program will
2438 start using the fast growth functions again.
2440 Here is an example:
2442 @smallexample
2443 @group
2444 void
2445 add_string (struct obstack *obstack, const char *ptr, int len)
2447   while (len > 0)
2448     @{
2449       int room = obstack_room (obstack);
2450       if (room == 0)
2451         @{
2452           /* @r{Not enough room.  Add one character slowly,}
2453              @r{which may copy to a new chunk and make room.}  */
2454           obstack_1grow (obstack, *ptr++);
2455           len--;
2456         @}
2457       else
2458         @{
2459           if (room > len)
2460             room = len;
2461           /* @r{Add fast as much as we have room for.} */
2462           len -= room;
2463           while (room-- > 0)
2464             obstack_1grow_fast (obstack, *ptr++);
2465         @}
2466     @}
2468 @end group
2469 @end smallexample
2471 @node Status of an Obstack
2472 @subsubsection Status of an Obstack
2473 @cindex obstack status
2474 @cindex status of obstack
2476 Here are functions that provide information on the current status of
2477 allocation in an obstack.  You can use them to learn about an object while
2478 still growing it.
2480 @deftypefun {void *} obstack_base (struct obstack *@var{obstack-ptr})
2481 @standards{GNU, obstack.h}
2482 @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acsafe{}}
2483 This function returns the tentative address of the beginning of the
2484 currently growing object in @var{obstack-ptr}.  If you finish the object
2485 immediately, it will have that address.  If you make it larger first, it
2486 may outgrow the current chunk---then its address will change!
2488 If no object is growing, this value says where the next object you
2489 allocate will start (once again assuming it fits in the current
2490 chunk).
2491 @end deftypefun
2493 @deftypefun {void *} obstack_next_free (struct obstack *@var{obstack-ptr})
2494 @standards{GNU, obstack.h}
2495 @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acsafe{}}
2496 This function returns the address of the first free byte in the current
2497 chunk of obstack @var{obstack-ptr}.  This is the end of the currently
2498 growing object.  If no object is growing, @code{obstack_next_free}
2499 returns the same value as @code{obstack_base}.
2500 @end deftypefun
2502 @deftypefun int obstack_object_size (struct obstack *@var{obstack-ptr})
2503 @standards{GNU, obstack.h}
2504 @c dup
2505 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
2506 This function returns the size in bytes of the currently growing object.
2507 This is equivalent to
2509 @smallexample
2510 obstack_next_free (@var{obstack-ptr}) - obstack_base (@var{obstack-ptr})
2511 @end smallexample
2512 @end deftypefun
2514 @node Obstacks Data Alignment
2515 @subsubsection Alignment of Data in Obstacks
2516 @cindex alignment (in obstacks)
2518 Each obstack has an @dfn{alignment boundary}; each object allocated in
2519 the obstack automatically starts on an address that is a multiple of the
2520 specified boundary.  By default, this boundary is aligned so that
2521 the object can hold any type of data.
2523 To access an obstack's alignment boundary, use the macro
2524 @code{obstack_alignment_mask}, whose function prototype looks like
2525 this:
2527 @deftypefn Macro int obstack_alignment_mask (struct obstack *@var{obstack-ptr})
2528 @standards{GNU, obstack.h}
2529 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2530 The value is a bit mask; a bit that is 1 indicates that the corresponding
2531 bit in the address of an object should be 0.  The mask value should be one
2532 less than a power of 2; the effect is that all object addresses are
2533 multiples of that power of 2.  The default value of the mask is a value
2534 that allows aligned objects to hold any type of data: for example, if
2535 its value is 3, any type of data can be stored at locations whose
2536 addresses are multiples of 4.  A mask value of 0 means an object can start
2537 on any multiple of 1 (that is, no alignment is required).
2539 The expansion of the macro @code{obstack_alignment_mask} is an lvalue,
2540 so you can alter the mask by assignment.  For example, this statement:
2542 @smallexample
2543 obstack_alignment_mask (obstack_ptr) = 0;
2544 @end smallexample
2546 @noindent
2547 has the effect of turning off alignment processing in the specified obstack.
2548 @end deftypefn
2550 Note that a change in alignment mask does not take effect until
2551 @emph{after} the next time an object is allocated or finished in the
2552 obstack.  If you are not growing an object, you can make the new
2553 alignment mask take effect immediately by calling @code{obstack_finish}.
2554 This will finish a zero-length object and then do proper alignment for
2555 the next object.
2557 @node Obstack Chunks
2558 @subsubsection Obstack Chunks
2559 @cindex efficiency of chunks
2560 @cindex chunks
2562 Obstacks work by allocating space for themselves in large chunks, and
2563 then parceling out space in the chunks to satisfy your requests.  Chunks
2564 are normally 4096 bytes long unless you specify a different chunk size.
2565 The chunk size includes 8 bytes of overhead that are not actually used
2566 for storing objects.  Regardless of the specified size, longer chunks
2567 will be allocated when necessary for long objects.
2569 The obstack library allocates chunks by calling the function
2570 @code{obstack_chunk_alloc}, which you must define.  When a chunk is no
2571 longer needed because you have freed all the objects in it, the obstack
2572 library frees the chunk by calling @code{obstack_chunk_free}, which you
2573 must also define.
2575 These two must be defined (as macros) or declared (as functions) in each
2576 source file that uses @code{obstack_init} (@pxref{Creating Obstacks}).
2577 Most often they are defined as macros like this:
2579 @smallexample
2580 #define obstack_chunk_alloc malloc
2581 #define obstack_chunk_free free
2582 @end smallexample
2584 Note that these are simple macros (no arguments).  Macro definitions with
2585 arguments will not work!  It is necessary that @code{obstack_chunk_alloc}
2586 or @code{obstack_chunk_free}, alone, expand into a function name if it is
2587 not itself a function name.
2589 If you allocate chunks with @code{malloc}, the chunk size should be a
2590 power of 2.  The default chunk size, 4096, was chosen because it is long
2591 enough to satisfy many typical requests on the obstack yet short enough
2592 not to waste too much memory in the portion of the last chunk not yet used.
2594 @deftypefn Macro int obstack_chunk_size (struct obstack *@var{obstack-ptr})
2595 @standards{GNU, obstack.h}
2596 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2597 This returns the chunk size of the given obstack.
2598 @end deftypefn
2600 Since this macro expands to an lvalue, you can specify a new chunk size by
2601 assigning it a new value.  Doing so does not affect the chunks already
2602 allocated, but will change the size of chunks allocated for that particular
2603 obstack in the future.  It is unlikely to be useful to make the chunk size
2604 smaller, but making it larger might improve efficiency if you are
2605 allocating many objects whose size is comparable to the chunk size.  Here
2606 is how to do so cleanly:
2608 @smallexample
2609 if (obstack_chunk_size (obstack_ptr) < @var{new-chunk-size})
2610   obstack_chunk_size (obstack_ptr) = @var{new-chunk-size};
2611 @end smallexample
2613 @node Summary of Obstacks
2614 @subsubsection Summary of Obstack Functions
2616 Here is a summary of all the functions associated with obstacks.  Each
2617 takes the address of an obstack (@code{struct obstack *}) as its first
2618 argument.
2620 @table @code
2621 @item void obstack_init (struct obstack *@var{obstack-ptr})
2622 Initialize use of an obstack.  @xref{Creating Obstacks}.
2624 @item void *obstack_alloc (struct obstack *@var{obstack-ptr}, int @var{size})
2625 Allocate an object of @var{size} uninitialized bytes.
2626 @xref{Allocation in an Obstack}.
2628 @item void *obstack_copy (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2629 Allocate an object of @var{size} bytes, with contents copied from
2630 @var{address}.  @xref{Allocation in an Obstack}.
2632 @item void *obstack_copy0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2633 Allocate an object of @var{size}+1 bytes, with @var{size} of them copied
2634 from @var{address}, followed by a null character at the end.
2635 @xref{Allocation in an Obstack}.
2637 @item void obstack_free (struct obstack *@var{obstack-ptr}, void *@var{object})
2638 Free @var{object} (and everything allocated in the specified obstack
2639 more recently than @var{object}).  @xref{Freeing Obstack Objects}.
2641 @item void obstack_blank (struct obstack *@var{obstack-ptr}, int @var{size})
2642 Add @var{size} uninitialized bytes to a growing object.
2643 @xref{Growing Objects}.
2645 @item void obstack_grow (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2646 Add @var{size} bytes, copied from @var{address}, to a growing object.
2647 @xref{Growing Objects}.
2649 @item void obstack_grow0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2650 Add @var{size} bytes, copied from @var{address}, to a growing object,
2651 and then add another byte containing a null character.  @xref{Growing
2652 Objects}.
2654 @item void obstack_1grow (struct obstack *@var{obstack-ptr}, char @var{data-char})
2655 Add one byte containing @var{data-char} to a growing object.
2656 @xref{Growing Objects}.
2658 @item void *obstack_finish (struct obstack *@var{obstack-ptr})
2659 Finalize the object that is growing and return its permanent address.
2660 @xref{Growing Objects}.
2662 @item int obstack_object_size (struct obstack *@var{obstack-ptr})
2663 Get the current size of the currently growing object.  @xref{Growing
2664 Objects}.
2666 @item void obstack_blank_fast (struct obstack *@var{obstack-ptr}, int @var{size})
2667 Add @var{size} uninitialized bytes to a growing object without checking
2668 that there is enough room.  @xref{Extra Fast Growing}.
2670 @item void obstack_1grow_fast (struct obstack *@var{obstack-ptr}, char @var{data-char})
2671 Add one byte containing @var{data-char} to a growing object without
2672 checking that there is enough room.  @xref{Extra Fast Growing}.
2674 @item int obstack_room (struct obstack *@var{obstack-ptr})
2675 Get the amount of room now available for growing the current object.
2676 @xref{Extra Fast Growing}.
2678 @item int obstack_alignment_mask (struct obstack *@var{obstack-ptr})
2679 The mask used for aligning the beginning of an object.  This is an
2680 lvalue.  @xref{Obstacks Data Alignment}.
2682 @item int obstack_chunk_size (struct obstack *@var{obstack-ptr})
2683 The size for allocating chunks.  This is an lvalue.  @xref{Obstack Chunks}.
2685 @item void *obstack_base (struct obstack *@var{obstack-ptr})
2686 Tentative starting address of the currently growing object.
2687 @xref{Status of an Obstack}.
2689 @item void *obstack_next_free (struct obstack *@var{obstack-ptr})
2690 Address just after the end of the currently growing object.
2691 @xref{Status of an Obstack}.
2692 @end table
2694 @node Variable Size Automatic
2695 @subsection Automatic Storage with Variable Size
2696 @cindex automatic freeing
2697 @cindex @code{alloca} function
2698 @cindex automatic storage with variable size
2700 The function @code{alloca} supports a kind of half-dynamic allocation in
2701 which blocks are allocated dynamically but freed automatically.
2703 Allocating a block with @code{alloca} is an explicit action; you can
2704 allocate as many blocks as you wish, and compute the size at run time.  But
2705 all the blocks are freed when you exit the function that @code{alloca} was
2706 called from, just as if they were automatic variables declared in that
2707 function.  There is no way to free the space explicitly.
2709 The prototype for @code{alloca} is in @file{stdlib.h}.  This function is
2710 a BSD extension.
2711 @pindex stdlib.h
2713 @deftypefun {void *} alloca (size_t @var{size})
2714 @standards{GNU, stdlib.h}
2715 @standards{BSD, stdlib.h}
2716 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2717 The return value of @code{alloca} is the address of a block of @var{size}
2718 bytes of memory, allocated in the stack frame of the calling function.
2719 @end deftypefun
2721 Do not use @code{alloca} inside the arguments of a function call---you
2722 will get unpredictable results, because the stack space for the
2723 @code{alloca} would appear on the stack in the middle of the space for
2724 the function arguments.  An example of what to avoid is @code{foo (x,
2725 alloca (4), y)}.
2726 @c This might get fixed in future versions of GCC, but that won't make
2727 @c it safe with compilers generally.
2729 @menu
2730 * Alloca Example::              Example of using @code{alloca}.
2731 * Advantages of Alloca::        Reasons to use @code{alloca}.
2732 * Disadvantages of Alloca::     Reasons to avoid @code{alloca}.
2733 * GNU C Variable-Size Arrays::  Only in GNU C, here is an alternative
2734                                  method of allocating dynamically and
2735                                  freeing automatically.
2736 @end menu
2738 @node Alloca Example
2739 @subsubsection @code{alloca} Example
2741 As an example of the use of @code{alloca}, here is a function that opens
2742 a file name made from concatenating two argument strings, and returns a
2743 file descriptor or minus one signifying failure:
2745 @smallexample
2747 open2 (char *str1, char *str2, int flags, int mode)
2749   char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
2750   stpcpy (stpcpy (name, str1), str2);
2751   return open (name, flags, mode);
2753 @end smallexample
2755 @noindent
2756 Here is how you would get the same results with @code{malloc} and
2757 @code{free}:
2759 @smallexample
2761 open2 (char *str1, char *str2, int flags, int mode)
2763   char *name = malloc (strlen (str1) + strlen (str2) + 1);
2764   int desc;
2765   if (name == 0)
2766     fatal ("virtual memory exceeded");
2767   stpcpy (stpcpy (name, str1), str2);
2768   desc = open (name, flags, mode);
2769   free (name);
2770   return desc;
2772 @end smallexample
2774 As you can see, it is simpler with @code{alloca}.  But @code{alloca} has
2775 other, more important advantages, and some disadvantages.
2777 @node Advantages of Alloca
2778 @subsubsection Advantages of @code{alloca}
2780 Here are the reasons why @code{alloca} may be preferable to @code{malloc}:
2782 @itemize @bullet
2783 @item
2784 Using @code{alloca} wastes very little space and is very fast.  (It is
2785 open-coded by the GNU C compiler.)
2787 @item
2788 Since @code{alloca} does not have separate pools for different sizes of
2789 blocks, space used for any size block can be reused for any other size.
2790 @code{alloca} does not cause memory fragmentation.
2792 @item
2793 @cindex longjmp
2794 Nonlocal exits done with @code{longjmp} (@pxref{Non-Local Exits})
2795 automatically free the space allocated with @code{alloca} when they exit
2796 through the function that called @code{alloca}.  This is the most
2797 important reason to use @code{alloca}.
2799 To illustrate this, suppose you have a function
2800 @code{open_or_report_error} which returns a descriptor, like
2801 @code{open}, if it succeeds, but does not return to its caller if it
2802 fails.  If the file cannot be opened, it prints an error message and
2803 jumps out to the command level of your program using @code{longjmp}.
2804 Let's change @code{open2} (@pxref{Alloca Example}) to use this
2805 subroutine:
2807 @smallexample
2809 open2 (char *str1, char *str2, int flags, int mode)
2811   char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
2812   stpcpy (stpcpy (name, str1), str2);
2813   return open_or_report_error (name, flags, mode);
2815 @end smallexample
2817 @noindent
2818 Because of the way @code{alloca} works, the memory it allocates is
2819 freed even when an error occurs, with no special effort required.
2821 By contrast, the previous definition of @code{open2} (which uses
2822 @code{malloc} and @code{free}) would develop a memory leak if it were
2823 changed in this way.  Even if you are willing to make more changes to
2824 fix it, there is no easy way to do so.
2825 @end itemize
2827 @node Disadvantages of Alloca
2828 @subsubsection Disadvantages of @code{alloca}
2830 @cindex @code{alloca} disadvantages
2831 @cindex disadvantages of @code{alloca}
2832 These are the disadvantages of @code{alloca} in comparison with
2833 @code{malloc}:
2835 @itemize @bullet
2836 @item
2837 If you try to allocate more memory than the machine can provide, you
2838 don't get a clean error message.  Instead you get a fatal signal like
2839 the one you would get from an infinite recursion; probably a
2840 segmentation violation (@pxref{Program Error Signals}).
2842 @item
2843 Some @nongnusystems{} fail to support @code{alloca}, so it is less
2844 portable.  However, a slower emulation of @code{alloca} written in C
2845 is available for use on systems with this deficiency.
2846 @end itemize
2848 @node GNU C Variable-Size Arrays
2849 @subsubsection GNU C Variable-Size Arrays
2850 @cindex variable-sized arrays
2852 In GNU C, you can replace most uses of @code{alloca} with an array of
2853 variable size.  Here is how @code{open2} would look then:
2855 @smallexample
2856 int open2 (char *str1, char *str2, int flags, int mode)
2858   char name[strlen (str1) + strlen (str2) + 1];
2859   stpcpy (stpcpy (name, str1), str2);
2860   return open (name, flags, mode);
2862 @end smallexample
2864 But @code{alloca} is not always equivalent to a variable-sized array, for
2865 several reasons:
2867 @itemize @bullet
2868 @item
2869 A variable size array's space is freed at the end of the scope of the
2870 name of the array.  The space allocated with @code{alloca}
2871 remains until the end of the function.
2873 @item
2874 It is possible to use @code{alloca} within a loop, allocating an
2875 additional block on each iteration.  This is impossible with
2876 variable-sized arrays.
2877 @end itemize
2879 @strong{NB:} If you mix use of @code{alloca} and variable-sized arrays
2880 within one function, exiting a scope in which a variable-sized array was
2881 declared frees all blocks allocated with @code{alloca} during the
2882 execution of that scope.
2885 @node Resizing the Data Segment
2886 @section Resizing the Data Segment
2888 The symbols in this section are declared in @file{unistd.h}.
2890 You will not normally use the functions in this section, because the
2891 functions described in @ref{Memory Allocation} are easier to use.  Those
2892 are interfaces to a @glibcadj{} memory allocator that uses the
2893 functions below itself.  The functions below are simple interfaces to
2894 system calls.
2896 @deftypefun int brk (void *@var{addr})
2897 @standards{BSD, unistd.h}
2898 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2900 @code{brk} sets the high end of the calling process' data segment to
2901 @var{addr}.
2903 The address of the end of a segment is defined to be the address of the
2904 last byte in the segment plus 1.
2906 The function has no effect if @var{addr} is lower than the low end of
2907 the data segment.  (This is considered success, by the way.)
2909 The function fails if it would cause the data segment to overlap another
2910 segment or exceed the process' data storage limit (@pxref{Limits on
2911 Resources}).
2913 The function is named for a common historical case where data storage
2914 and the stack are in the same segment.  Data storage allocation grows
2915 upward from the bottom of the segment while the stack grows downward
2916 toward it from the top of the segment and the curtain between them is
2917 called the @dfn{break}.
2919 The return value is zero on success.  On failure, the return value is
2920 @code{-1} and @code{errno} is set accordingly.  The following @code{errno}
2921 values are specific to this function:
2923 @table @code
2924 @item ENOMEM
2925 The request would cause the data segment to overlap another segment or
2926 exceed the process' data storage limit.
2927 @end table
2929 @c The Brk system call in Linux (as opposed to the GNU C Library function)
2930 @c is considerably different.  It always returns the new end of the data
2931 @c segment, whether it succeeds or fails.  The GNU C library Brk determines
2932 @c it's a failure if and only if the system call returns an address less
2933 @c than the address requested.
2935 @end deftypefun
2938 @deftypefun void *sbrk (ptrdiff_t @var{delta})
2939 @standards{BSD, unistd.h}
2940 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2942 This function is the same as @code{brk} except that you specify the new
2943 end of the data segment as an offset @var{delta} from the current end
2944 and on success the return value is the address of the resulting end of
2945 the data segment instead of zero.
2947 This means you can use @samp{sbrk(0)} to find out what the current end
2948 of the data segment is.
2950 @end deftypefun
2952 @node Memory Protection
2953 @section Memory Protection
2954 @cindex memory protection
2955 @cindex page protection
2956 @cindex protection flags
2958 When a page is mapped using @code{mmap}, page protection flags can be
2959 specified using the protection flags argument.  @xref{Memory-mapped
2960 I/O}.
2962 The following flags are available:
2964 @vtable @code
2965 @item PROT_WRITE
2966 @standards{POSIX, sys/mman.h}
2967 The memory can be written to.
2969 @item PROT_READ
2970 @standards{POSIX, sys/mman.h}
2971 The memory can be read.  On some architectures, this flag implies that
2972 the memory can be executed as well (as if @code{PROT_EXEC} had been
2973 specified at the same time).
2975 @item PROT_EXEC
2976 @standards{POSIX, sys/mman.h}
2977 The memory can be used to store instructions which can then be executed.
2978 On most architectures, this flag implies that the memory can be read (as
2979 if @code{PROT_READ} had been specified).
2981 @item PROT_NONE
2982 @standards{POSIX, sys/mman.h}
2983 This flag must be specified on its own.
2985 The memory is reserved, but cannot be read, written, or executed.  If
2986 this flag is specified in a call to @code{mmap}, a virtual memory area
2987 will be set aside for future use in the process, and @code{mmap} calls
2988 without the @code{MAP_FIXED} flag will not use it for subsequent
2989 allocations.  For anonymous mappings, the kernel will not reserve any
2990 physical memory for the allocation at the time the mapping is created.
2991 @end vtable
2993 The operating system may keep track of these flags separately even if
2994 the underlying hardware treats them the same for the purposes of access
2995 checking (as happens with @code{PROT_READ} and @code{PROT_EXEC} on some
2996 platforms).  On GNU systems, @code{PROT_EXEC} always implies
2997 @code{PROT_READ}, so that users can view the machine code which is
2998 executing on their system.
3000 Inappropriate access will cause a segfault (@pxref{Program Error
3001 Signals}).
3003 After allocation, protection flags can be changed using the
3004 @code{mprotect} function.
3006 @deftypefun int mprotect (void *@var{address}, size_t @var{length}, int @var{protection})
3007 @standards{POSIX, sys/mman.h}
3008 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3010 A successful call to the @code{mprotect} function changes the protection
3011 flags of at least @var{length} bytes of memory, starting at
3012 @var{address}.
3014 @var{address} must be aligned to the page size for the mapping.  The
3015 system page size can be obtained by calling @code{sysconf} with the
3016 @code{_SC_PAGESIZE} parameter (@pxref{Sysconf Definition}).  The system
3017 page size is the granularity in which the page protection of anonymous
3018 memory mappings and most file mappings can be changed.  Memory which is
3019 mapped from special files or devices may have larger page granularity
3020 than the system page size and may require larger alignment.
3022 @var{length} is the number of bytes whose protection flags must be
3023 changed.  It is automatically rounded up to the next multiple of the
3024 system page size.
3026 @var{protection} is a combination of the @code{PROT_*} flags described
3027 above.
3029 The @code{mprotect} function returns @math{0} on success and @math{-1}
3030 on failure.
3032 The following @code{errno} error conditions are defined for this
3033 function:
3035 @table @code
3036 @item ENOMEM
3037 The system was not able to allocate resources to fulfill the request.
3038 This can happen if there is not enough physical memory in the system for
3039 the allocation of backing storage.  The error can also occur if the new
3040 protection flags would cause the memory region to be split from its
3041 neighbors, and the process limit for the number of such distinct memory
3042 regions would be exceeded.
3044 @item EINVAL
3045 @var{address} is not properly aligned to a page boundary for the
3046 mapping, or @var{length} (after rounding up to the system page size) is
3047 not a multiple of the applicable page size for the mapping, or the
3048 combination of flags in @var{protection} is not valid.
3050 @item EACCES
3051 The file for a file-based mapping was not opened with open flags which
3052 are compatible with @var{protection}.
3054 @item EPERM
3055 The system security policy does not allow a mapping with the specified
3056 flags.  For example, mappings which are both @code{PROT_EXEC} and
3057 @code{PROT_WRITE} at the same time might not be allowed.
3058 @end table
3059 @end deftypefun
3061 If the @code{mprotect} function is used to make a region of memory
3062 inaccessible by specifying the @code{PROT_NONE} protection flag and
3063 access is later restored, the memory retains its previous contents.
3065 On some systems, it may not be possible to specify additional flags
3066 which were not present when the mapping was first created.  For example,
3067 an attempt to make a region of memory executable could fail if the
3068 initial protection flags were @samp{PROT_READ | PROT_WRITE}.
3070 In general, the @code{mprotect} function can be used to change any
3071 process memory, no matter how it was allocated.  However, portable use
3072 of the function requires that it is only used with memory regions
3073 returned by @code{mmap} or @code{mmap64}.
3075 @subsection Memory Protection Keys
3077 @cindex memory protection key
3078 @cindex protection key
3079 @cindex MPK
3080 On some systems, further restrictions can be added to specific pages
3081 using @dfn{memory protection keys}.  These restrictions work as follows:
3083 @itemize @bullet
3084 @item
3085 All memory pages are associated with a protection key.  The default
3086 protection key does not cause any additional protections to be applied
3087 during memory accesses.  New keys can be allocated with the
3088 @code{pkey_alloc} function, and applied to pages using
3089 @code{pkey_mprotect}.
3091 @item
3092 Each thread has a set of separate access right restriction for each
3093 protection key.  These access rights can be manipulated using the
3094 @code{pkey_set} and @code{pkey_get} functions.
3096 @item
3097 During a memory access, the system obtains the protection key for the
3098 accessed page and uses that to determine the applicable access rights,
3099 as configured for the current thread.  If the access is restricted, a
3100 segmentation fault is the result ((@pxref{Program Error Signals}).
3101 These checks happen in addition to the @code{PROT_}* protection flags
3102 set by @code{mprotect} or @code{pkey_mprotect}.
3103 @end itemize
3105 New threads and subprocesses inherit the access rights of the current
3106 thread.  If a protection key is allocated subsequently, existing threads
3107 (except the current) will use an unspecified system default for the
3108 access rights associated with newly allocated keys.
3110 Upon entering a signal handler, the system resets the access rights of
3111 the current thread so that pages with the default key can be accessed,
3112 but the access rights for other protection keys are unspecified.
3114 Applications are expected to allocate a key once using
3115 @code{pkey_alloc}, and apply the key to memory regions which need
3116 special protection with @code{pkey_mprotect}:
3118 @smallexample
3119   int key = pkey_alloc (0, PKEY_DISABLE_ACCESS);
3120   if (key < 0)
3121     /* Perform error checking, including fallback for lack of support.  */
3122     ...;
3124   /* Apply the key to a special memory region used to store critical
3125      data.  */
3126   if (pkey_mprotect (region, region_length,
3127                      PROT_READ | PROT_WRITE, key) < 0)
3128     ...; /* Perform error checking (generally fatal).  */
3129 @end smallexample
3131 If the key allocation fails due to lack of support for memory protection
3132 keys, the @code{pkey_mprotect} call can usually be skipped.  In this
3133 case, the region will not be protected by default.  It is also possible
3134 to call @code{pkey_mprotect} with a key value of @math{-1}, in which
3135 case it will behave in the same way as @code{mprotect}.
3137 After key allocation assignment to memory pages, @code{pkey_set} can be
3138 used to temporarily acquire access to the memory region and relinquish
3139 it again:
3141 @smallexample
3142   if (key >= 0 && pkey_set (key, 0) < 0)
3143     ...; /* Perform error checking (generally fatal).  */
3144   /* At this point, the current thread has read-write access to the
3145      memory region.  */
3146   ...
3147   /* Revoke access again.  */
3148   if (key >= 0 && pkey_set (key, PKEY_DISABLE_ACCESS) < 0)
3149     ...; /* Perform error checking (generally fatal).  */
3150 @end smallexample
3152 In this example, a negative key value indicates that no key had been
3153 allocated, which means that the system lacks support for memory
3154 protection keys and it is not necessary to change the the access rights
3155 of the current thread (because it always has access).
3157 Compared to using @code{mprotect} to change the page protection flags,
3158 this approach has two advantages: It is thread-safe in the sense that
3159 the access rights are only changed for the current thread, so another
3160 thread which changes its own access rights concurrently to gain access
3161 to the mapping will not suddenly see its access rights revoked.  And
3162 @code{pkey_set} typically does not involve a call into the kernel and a
3163 context switch, so it is more efficient.
3165 @deftypefun int pkey_alloc (unsigned int @var{flags}, unsigned int @var{restrictions})
3166 @standards{Linux, sys/mman.h}
3167 @safety{@prelim{}@mtsafe{}@assafe{}@acunsafe{@acucorrupt{}}}
3168 Allocate a new protection key.  The @var{flags} argument is reserved and
3169 must be zero.  The @var{restrictions} argument specifies access rights
3170 which are applied to the current thread (as if with @code{pkey_set}
3171 below).  Access rights of other threads are not changed.
3173 The function returns the new protection key, a non-negative number, or
3174 @math{-1} on error.
3176 The following @code{errno} error conditions are defined for this
3177 function:
3179 @table @code
3180 @item ENOSYS
3181 The system does not implement memory protection keys.
3183 @item EINVAL
3184 The @var{flags} argument is not zero.
3186 The @var{restrictions} argument is invalid.
3188 The system does not implement memory protection keys or runs in a mode
3189 in which memory protection keys are disabled.
3191 @item ENOSPC
3192 All available protection keys already have been allocated.
3194 The system does not implement memory protection keys or runs in a mode
3195 in which memory protection keys are disabled.
3197 @end table
3198 @end deftypefun
3200 @deftypefun int pkey_free (int @var{key})
3201 @standards{Linux, sys/mman.h}
3202 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3203 Deallocate the protection key, so that it can be reused by
3204 @code{pkey_alloc}.
3206 Calling this function does not change the access rights of the freed
3207 protection key.  The calling thread and other threads may retain access
3208 to it, even if it is subsequently allocated again.  For this reason, it
3209 is not recommended to call the @code{pkey_free} function.
3211 @table @code
3212 @item ENOSYS
3213 The system does not implement memory protection keys.
3215 @item EINVAL
3216 The @var{key} argument is not a valid protection key.
3217 @end table
3218 @end deftypefun
3220 @deftypefun int pkey_mprotect (void *@var{address}, size_t @var{length}, int @var{protection}, int @var{key})
3221 @standards{Linux, sys/mman.h}
3222 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3223 Similar to @code{mprotect}, but also set the memory protection key for
3224 the memory region to @code{key}.
3226 Some systems use memory protection keys to emulate certain combinations
3227 of @var{protection} flags.  Under such circumstances, specifying an
3228 explicit protection key may behave as if additional flags have been
3229 specified in @var{protection}, even though this does not happen with the
3230 default protection key.  For example, some systems can support
3231 @code{PROT_EXEC}-only mappings only with a default protection key, and
3232 memory with a key which was allocated using @code{pkey_alloc} will still
3233 be readable if @code{PROT_EXEC} is specified without @code{PROT_READ}.
3235 If @var{key} is @math{-1}, the default protection key is applied to the
3236 mapping, just as if @code{mprotect} had been called.
3238 The @code{pkey_mprotect} function returns @math{0} on success and
3239 @math{-1} on failure.  The same @code{errno} error conditions as for
3240 @code{mprotect} are defined for this function, with the following
3241 addition:
3243 @table @code
3244 @item EINVAL
3245 The @var{key} argument is not @math{-1} or a valid memory protection
3246 key allocated using @code{pkey_alloc}.
3248 @item ENOSYS
3249 The system does not implement memory protection keys, and @var{key} is
3250 not @math{-1}.
3251 @end table
3252 @end deftypefun
3254 @deftypefun int pkey_set (int @var{key}, unsigned int @var{rights})
3255 @standards{Linux, sys/mman.h}
3256 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3257 Change the access rights of the current thread for memory pages with the
3258 protection key @var{key} to @var{rights}.  If @var{rights} is zero, no
3259 additional access restrictions on top of the page protection flags are
3260 applied.  Otherwise, @var{rights} is a combination of the following
3261 flags:
3263 @vtable @code
3264 @item PKEY_DISABLE_WRITE
3265 @standards{Linux, sys/mman.h}
3266 Subsequent attempts to write to memory with the specified protection
3267 key will fault.
3269 @item PKEY_DISABLE_ACCESS
3270 @standards{Linux, sys/mman.h}
3271 Subsequent attempts to write to or read from memory with the specified
3272 protection key will fault.
3273 @end vtable
3275 Operations not specified as flags are not restricted.  In particular,
3276 this means that the memory region will remain executable if it was
3277 mapped with the @code{PROT_EXEC} protection flag and
3278 @code{PKEY_DISABLE_ACCESS} has been specified.
3280 Calling the @code{pkey_set} function with a protection key which was not
3281 allocated by @code{pkey_alloc} results in undefined behavior.  This
3282 means that calling this function on systems which do not support memory
3283 protection keys is undefined.
3285 The @code{pkey_set} function returns @math{0} on success and @math{-1}
3286 on failure.
3288 The following @code{errno} error conditions are defined for this
3289 function:
3291 @table @code
3292 @item EINVAL
3293 The system does not support the access rights restrictions expressed in
3294 the @var{rights} argument.
3295 @end table
3296 @end deftypefun
3298 @deftypefun int pkey_get (int @var{key})
3299 @standards{Linux, sys/mman.h}
3300 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3301 Return the access rights of the current thread for memory pages with
3302 protection key @var{key}.  The return value is zero or a combination of
3303 the @code{PKEY_DISABLE_}* flags; see the @code{pkey_set} function.
3305 Calling the @code{pkey_get} function with a protection key which was not
3306 allocated by @code{pkey_alloc} results in undefined behavior.  This
3307 means that calling this function on systems which do not support memory
3308 protection keys is undefined.
3309 @end deftypefun
3311 @node Locking Pages
3312 @section Locking Pages
3313 @cindex locking pages
3314 @cindex memory lock
3315 @cindex paging
3317 You can tell the system to associate a particular virtual memory page
3318 with a real page frame and keep it that way --- i.e., cause the page to
3319 be paged in if it isn't already and mark it so it will never be paged
3320 out and consequently will never cause a page fault.  This is called
3321 @dfn{locking} a page.
3323 The functions in this chapter lock and unlock the calling process'
3324 pages.
3326 @menu
3327 * Why Lock Pages::                Reasons to read this section.
3328 * Locked Memory Details::         Everything you need to know locked
3329                                     memory
3330 * Page Lock Functions::           Here's how to do it.
3331 @end menu
3333 @node Why Lock Pages
3334 @subsection Why Lock Pages
3336 Because page faults cause paged out pages to be paged in transparently,
3337 a process rarely needs to be concerned about locking pages.  However,
3338 there are two reasons people sometimes are:
3340 @itemize @bullet
3342 @item
3343 Speed.  A page fault is transparent only insofar as the process is not
3344 sensitive to how long it takes to do a simple memory access.  Time-critical
3345 processes, especially realtime processes, may not be able to wait or
3346 may not be able to tolerate variance in execution speed.
3347 @cindex realtime processing
3348 @cindex speed of execution
3350 A process that needs to lock pages for this reason probably also needs
3351 priority among other processes for use of the CPU.  @xref{Priority}.
3353 In some cases, the programmer knows better than the system's demand
3354 paging allocator which pages should remain in real memory to optimize
3355 system performance.  In this case, locking pages can help.
3357 @item
3358 Privacy.  If you keep secrets in virtual memory and that virtual memory
3359 gets paged out, that increases the chance that the secrets will get out.
3360 If a passphrase gets written out to disk swap space, for example, it might
3361 still be there long after virtual and real memory have been wiped clean.
3363 @end itemize
3365 Be aware that when you lock a page, that's one fewer page frame that can
3366 be used to back other virtual memory (by the same or other processes),
3367 which can mean more page faults, which means the system runs more
3368 slowly.  In fact, if you lock enough memory, some programs may not be
3369 able to run at all for lack of real memory.
3371 @node Locked Memory Details
3372 @subsection Locked Memory Details
3374 A memory lock is associated with a virtual page, not a real frame.  The
3375 paging rule is: If a frame backs at least one locked page, don't page it
3376 out.
3378 Memory locks do not stack.  I.e., you can't lock a particular page twice
3379 so that it has to be unlocked twice before it is truly unlocked.  It is
3380 either locked or it isn't.
3382 A memory lock persists until the process that owns the memory explicitly
3383 unlocks it.  (But process termination and exec cause the virtual memory
3384 to cease to exist, which you might say means it isn't locked any more).
3386 Memory locks are not inherited by child processes.  (But note that on a
3387 modern Unix system, immediately after a fork, the parent's and the
3388 child's virtual address space are backed by the same real page frames,
3389 so the child enjoys the parent's locks).  @xref{Creating a Process}.
3391 Because of its ability to impact other processes, only the superuser can
3392 lock a page.  Any process can unlock its own page.
3394 The system sets limits on the amount of memory a process can have locked
3395 and the amount of real memory it can have dedicated to it.  @xref{Limits
3396 on Resources}.
3398 In Linux, locked pages aren't as locked as you might think.
3399 Two virtual pages that are not shared memory can nonetheless be backed
3400 by the same real frame.  The kernel does this in the name of efficiency
3401 when it knows both virtual pages contain identical data, and does it
3402 even if one or both of the virtual pages are locked.
3404 But when a process modifies one of those pages, the kernel must get it a
3405 separate frame and fill it with the page's data.  This is known as a
3406 @dfn{copy-on-write page fault}.  It takes a small amount of time and in
3407 a pathological case, getting that frame may require I/O.
3408 @cindex copy-on-write page fault
3409 @cindex page fault, copy-on-write
3411 To make sure this doesn't happen to your program, don't just lock the
3412 pages.  Write to them as well, unless you know you won't write to them
3413 ever.  And to make sure you have pre-allocated frames for your stack,
3414 enter a scope that declares a C automatic variable larger than the
3415 maximum stack size you will need, set it to something, then return from
3416 its scope.
3418 @node Page Lock Functions
3419 @subsection Functions To Lock And Unlock Pages
3421 The symbols in this section are declared in @file{sys/mman.h}.  These
3422 functions are defined by POSIX.1b, but their availability depends on
3423 your kernel.  If your kernel doesn't allow these functions, they exist
3424 but always fail.  They @emph{are} available with a Linux kernel.
3426 @strong{Portability Note:} POSIX.1b requires that when the @code{mlock}
3427 and @code{munlock} functions are available, the file @file{unistd.h}
3428 define the macro @code{_POSIX_MEMLOCK_RANGE} and the file
3429 @code{limits.h} define the macro @code{PAGESIZE} to be the size of a
3430 memory page in bytes.  It requires that when the @code{mlockall} and
3431 @code{munlockall} functions are available, the @file{unistd.h} file
3432 define the macro @code{_POSIX_MEMLOCK}.  @Theglibc{} conforms to
3433 this requirement.
3435 @deftypefun int mlock (const void *@var{addr}, size_t @var{len})
3436 @standards{POSIX.1b, sys/mman.h}
3437 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3439 @code{mlock} locks a range of the calling process' virtual pages.
3441 The range of memory starts at address @var{addr} and is @var{len} bytes
3442 long.  Actually, since you must lock whole pages, it is the range of
3443 pages that include any part of the specified range.
3445 When the function returns successfully, each of those pages is backed by
3446 (connected to) a real frame (is resident) and is marked to stay that
3447 way.  This means the function may cause page-ins and have to wait for
3448 them.
3450 When the function fails, it does not affect the lock status of any
3451 pages.
3453 The return value is zero if the function succeeds.  Otherwise, it is
3454 @code{-1} and @code{errno} is set accordingly.  @code{errno} values
3455 specific to this function are:
3457 @table @code
3458 @item ENOMEM
3459 @itemize @bullet
3460 @item
3461 At least some of the specified address range does not exist in the
3462 calling process' virtual address space.
3463 @item
3464 The locking would cause the process to exceed its locked page limit.
3465 @end itemize
3467 @item EPERM
3468 The calling process is not superuser.
3470 @item EINVAL
3471 @var{len} is not positive.
3473 @item ENOSYS
3474 The kernel does not provide @code{mlock} capability.
3476 @end table
3477 @end deftypefun
3479 @deftypefun int mlock2 (const void *@var{addr}, size_t @var{len}, unsigned int @var{flags})
3480 @standards{Linux, sys/mman.h}
3481 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3483 This function is similar to @code{mlock}.  If @var{flags} is zero, a
3484 call to @code{mlock2} behaves exactly as the equivalent call to @code{mlock}.
3486 The @var{flags} argument must be a combination of zero or more of the
3487 following flags:
3489 @vtable @code
3490 @item MLOCK_ONFAULT
3491 @standards{Linux, sys/mman.h}
3492 Only those pages in the specified address range which are already in
3493 memory are locked immediately.  Additional pages in the range are
3494 automatically locked in case of a page fault and allocation of memory.
3495 @end vtable
3497 Like @code{mlock}, @code{mlock2} returns zero on success and @code{-1}
3498 on failure, setting @code{errno} accordingly.  Additional @code{errno}
3499 values defined for @code{mlock2} are:
3501 @table @code
3502 @item EINVAL
3503 The specified (non-zero) @var{flags} argument is not supported by this
3504 system.
3505 @end table
3506 @end deftypefun
3508 You can lock @emph{all} a process' memory with @code{mlockall}.  You
3509 unlock memory with @code{munlock} or @code{munlockall}.
3511 To avoid all page faults in a C program, you have to use
3512 @code{mlockall}, because some of the memory a program uses is hidden
3513 from the C code, e.g. the stack and automatic variables, and you
3514 wouldn't know what address to tell @code{mlock}.
3516 @deftypefun int munlock (const void *@var{addr}, size_t @var{len})
3517 @standards{POSIX.1b, sys/mman.h}
3518 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3520 @code{munlock} unlocks a range of the calling process' virtual pages.
3522 @code{munlock} is the inverse of @code{mlock} and functions completely
3523 analogously to @code{mlock}, except that there is no @code{EPERM}
3524 failure.
3526 @end deftypefun
3528 @deftypefun int mlockall (int @var{flags})
3529 @standards{POSIX.1b, sys/mman.h}
3530 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3532 @code{mlockall} locks all the pages in a process' virtual memory address
3533 space, and/or any that are added to it in the future.  This includes the
3534 pages of the code, data and stack segment, as well as shared libraries,
3535 user space kernel data, shared memory, and memory mapped files.
3537 @var{flags} is a string of single bit flags represented by the following
3538 macros.  They tell @code{mlockall} which of its functions you want.  All
3539 other bits must be zero.
3541 @vtable @code
3543 @item MCL_CURRENT
3544 Lock all pages which currently exist in the calling process' virtual
3545 address space.
3547 @item MCL_FUTURE
3548 Set a mode such that any pages added to the process' virtual address
3549 space in the future will be locked from birth.  This mode does not
3550 affect future address spaces owned by the same process so exec, which
3551 replaces a process' address space, wipes out @code{MCL_FUTURE}.
3552 @xref{Executing a File}.
3554 @end vtable
3556 When the function returns successfully, and you specified
3557 @code{MCL_CURRENT}, all of the process' pages are backed by (connected
3558 to) real frames (they are resident) and are marked to stay that way.
3559 This means the function may cause page-ins and have to wait for them.
3561 When the process is in @code{MCL_FUTURE} mode because it successfully
3562 executed this function and specified @code{MCL_CURRENT}, any system call
3563 by the process that requires space be added to its virtual address space
3564 fails with @code{errno} = @code{ENOMEM} if locking the additional space
3565 would cause the process to exceed its locked page limit.  In the case
3566 that the address space addition that can't be accommodated is stack
3567 expansion, the stack expansion fails and the kernel sends a
3568 @code{SIGSEGV} signal to the process.
3570 When the function fails, it does not affect the lock status of any pages
3571 or the future locking mode.
3573 The return value is zero if the function succeeds.  Otherwise, it is
3574 @code{-1} and @code{errno} is set accordingly.  @code{errno} values
3575 specific to this function are:
3577 @table @code
3578 @item ENOMEM
3579 @itemize @bullet
3580 @item
3581 At least some of the specified address range does not exist in the
3582 calling process' virtual address space.
3583 @item
3584 The locking would cause the process to exceed its locked page limit.
3585 @end itemize
3587 @item EPERM
3588 The calling process is not superuser.
3590 @item EINVAL
3591 Undefined bits in @var{flags} are not zero.
3593 @item ENOSYS
3594 The kernel does not provide @code{mlockall} capability.
3596 @end table
3598 You can lock just specific pages with @code{mlock}.  You unlock pages
3599 with @code{munlockall} and @code{munlock}.
3601 @end deftypefun
3604 @deftypefun int munlockall (void)
3605 @standards{POSIX.1b, sys/mman.h}
3606 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3608 @code{munlockall} unlocks every page in the calling process' virtual
3609 address space and turns off @code{MCL_FUTURE} future locking mode.
3611 The return value is zero if the function succeeds.  Otherwise, it is
3612 @code{-1} and @code{errno} is set accordingly.  The only way this
3613 function can fail is for generic reasons that all functions and system
3614 calls can fail, so there are no specific @code{errno} values.
3616 @end deftypefun
3621 @ignore
3622 @c This was never actually implemented.  -zw
3623 @node Relocating Allocator
3624 @section Relocating Allocator
3626 @cindex relocating memory allocator
3627 Any system of dynamic memory allocation has overhead: the amount of
3628 space it uses is more than the amount the program asks for.  The
3629 @dfn{relocating memory allocator} achieves very low overhead by moving
3630 blocks in memory as necessary, on its own initiative.
3632 @c @menu
3633 @c * Relocator Concepts::               How to understand relocating allocation.
3634 @c * Using Relocator::          Functions for relocating allocation.
3635 @c @end menu
3637 @node Relocator Concepts
3638 @subsection Concepts of Relocating Allocation
3640 @ifinfo
3641 The @dfn{relocating memory allocator} achieves very low overhead by
3642 moving blocks in memory as necessary, on its own initiative.
3643 @end ifinfo
3645 When you allocate a block with @code{malloc}, the address of the block
3646 never changes unless you use @code{realloc} to change its size.  Thus,
3647 you can safely store the address in various places, temporarily or
3648 permanently, as you like.  This is not safe when you use the relocating
3649 memory allocator, because any and all relocatable blocks can move
3650 whenever you allocate memory in any fashion.  Even calling @code{malloc}
3651 or @code{realloc} can move the relocatable blocks.
3653 @cindex handle
3654 For each relocatable block, you must make a @dfn{handle}---a pointer
3655 object in memory, designated to store the address of that block.  The
3656 relocating allocator knows where each block's handle is, and updates the
3657 address stored there whenever it moves the block, so that the handle
3658 always points to the block.  Each time you access the contents of the
3659 block, you should fetch its address anew from the handle.
3661 To call any of the relocating allocator functions from a signal handler
3662 is almost certainly incorrect, because the signal could happen at any
3663 time and relocate all the blocks.  The only way to make this safe is to
3664 block the signal around any access to the contents of any relocatable
3665 block---not a convenient mode of operation.  @xref{Nonreentrancy}.
3667 @node Using Relocator
3668 @subsection Allocating and Freeing Relocatable Blocks
3670 @pindex malloc.h
3671 In the descriptions below, @var{handleptr} designates the address of the
3672 handle.  All the functions are declared in @file{malloc.h}; all are GNU
3673 extensions.
3675 @comment malloc.h
3676 @comment GNU
3677 @c @deftypefun {void *} r_alloc (void **@var{handleptr}, size_t @var{size})
3678 This function allocates a relocatable block of size @var{size}.  It
3679 stores the block's address in @code{*@var{handleptr}} and returns
3680 a non-null pointer to indicate success.
3682 If @code{r_alloc} can't get the space needed, it stores a null pointer
3683 in @code{*@var{handleptr}}, and returns a null pointer.
3684 @end deftypefun
3686 @comment malloc.h
3687 @comment GNU
3688 @c @deftypefun void r_alloc_free (void **@var{handleptr})
3689 This function is the way to free a relocatable block.  It frees the
3690 block that @code{*@var{handleptr}} points to, and stores a null pointer
3691 in @code{*@var{handleptr}} to show it doesn't point to an allocated
3692 block any more.
3693 @end deftypefun
3695 @comment malloc.h
3696 @comment GNU
3697 @c @deftypefun {void *} r_re_alloc (void **@var{handleptr}, size_t @var{size})
3698 The function @code{r_re_alloc} adjusts the size of the block that
3699 @code{*@var{handleptr}} points to, making it @var{size} bytes long.  It
3700 stores the address of the resized block in @code{*@var{handleptr}} and
3701 returns a non-null pointer to indicate success.
3703 If enough memory is not available, this function returns a null pointer
3704 and does not modify @code{*@var{handleptr}}.
3705 @end deftypefun
3706 @end ignore
3711 @ignore
3712 @comment No longer available...
3714 @comment @node Memory Warnings
3715 @comment @section Memory Usage Warnings
3716 @comment @cindex memory usage warnings
3717 @comment @cindex warnings of memory almost full
3719 @pindex malloc.c
3720 You can ask for warnings as the program approaches running out of memory
3721 space, by calling @code{memory_warnings}.  This tells @code{malloc} to
3722 check memory usage every time it asks for more memory from the operating
3723 system.  This is a GNU extension declared in @file{malloc.h}.
3725 @comment malloc.h
3726 @comment GNU
3727 @comment @deftypefun void memory_warnings (void *@var{start}, void (*@var{warn-func}) (const char *))
3728 Call this function to request warnings for nearing exhaustion of virtual
3729 memory.
3731 The argument @var{start} says where data space begins, in memory.  The
3732 allocator compares this against the last address used and against the
3733 limit of data space, to determine the fraction of available memory in
3734 use.  If you supply zero for @var{start}, then a default value is used
3735 which is right in most circumstances.
3737 For @var{warn-func}, supply a function that @code{malloc} can call to
3738 warn you.  It is called with a string (a warning message) as argument.
3739 Normally it ought to display the string for the user to read.
3740 @end deftypefun
3742 The warnings come when memory becomes 75% full, when it becomes 85%
3743 full, and when it becomes 95% full.  Above 95% you get another warning
3744 each time memory usage increases.
3746 @end ignore