As a minor cleanup remove the (r)index defines from include/string.h as
[glibc.git] / manual / memory.texi
blob38d3c3a4bb44d0eaaa859dc67f9a952bf3dfe6a4
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 * Locking Pages::               Preventing page faults
21 @end menu
23 Memory mapped I/O is not discussed in this chapter.  @xref{Memory-mapped I/O}.
27 @node Memory Concepts
28 @section Process Memory Concepts
30 One of the most basic resources a process has available to it is memory.
31 There are a lot of different ways systems organize memory, but in a
32 typical one, each process has one linear virtual address space, with
33 addresses running from zero to some huge maximum.  It need not be
34 contiguous; i.e., not all of these addresses actually can be used to
35 store data.
37 The virtual memory is divided into pages (4 kilobytes is typical).
38 Backing each page of virtual memory is a page of real memory (called a
39 @dfn{frame}) or some secondary storage, usually disk space.  The disk
40 space might be swap space or just some ordinary disk file.  Actually, a
41 page of all zeroes sometimes has nothing at all backing it -- there's
42 just a flag saying it is all zeroes.
43 @cindex page frame
44 @cindex frame, real memory
45 @cindex swap space
46 @cindex page, virtual memory
48 The same frame of real memory or backing store can back multiple virtual
49 pages belonging to multiple processes.  This is normally the case, for
50 example, with virtual memory occupied by @glibcadj{} code.  The same
51 real memory frame containing the @code{printf} function backs a virtual
52 memory page in each of the existing processes that has a @code{printf}
53 call in its program.
55 In order for a program to access any part of a virtual page, the page
56 must at that moment be backed by (``connected to'') a real frame.  But
57 because there is usually a lot more virtual memory than real memory, the
58 pages must move back and forth between real memory and backing store
59 regularly, coming into real memory when a process needs to access them
60 and then retreating to backing store when not needed anymore.  This
61 movement is called @dfn{paging}.
63 When a program attempts to access a page which is not at that moment
64 backed by real memory, this is known as a @dfn{page fault}.  When a page
65 fault occurs, the kernel suspends the process, places the page into a
66 real page frame (this is called ``paging in'' or ``faulting in''), then
67 resumes the process so that from the process' point of view, the page
68 was in real memory all along.  In fact, to the process, all pages always
69 seem to be in real memory.  Except for one thing: the elapsed execution
70 time of an instruction that would normally be a few nanoseconds is
71 suddenly much, much, longer (because the kernel normally has to do I/O
72 to complete the page-in).  For programs sensitive to that, the functions
73 described in @ref{Locking Pages} can control it.
74 @cindex page fault
75 @cindex paging
77 Within each virtual address space, a process has to keep track of what
78 is at which addresses, and that process is called memory allocation.
79 Allocation usually brings to mind meting out scarce resources, but in
80 the case of virtual memory, that's not a major goal, because there is
81 generally much more of it than anyone needs.  Memory allocation within a
82 process is mainly just a matter of making sure that the same byte of
83 memory isn't used to store two different things.
85 Processes allocate memory in two major ways: by exec and
86 programmatically.  Actually, forking is a third way, but it's not very
87 interesting.  @xref{Creating a Process}.
89 Exec is the operation of creating a virtual address space for a process,
90 loading its basic program into it, and executing the program.  It is
91 done by the ``exec'' family of functions (e.g. @code{execl}).  The
92 operation takes a program file (an executable), it allocates space to
93 load all the data in the executable, loads it, and transfers control to
94 it.  That data is most notably the instructions of the program (the
95 @dfn{text}), but also literals and constants in the program and even
96 some variables: C variables with the static storage class (@pxref{Memory
97 Allocation and C}).
98 @cindex executable
99 @cindex literals
100 @cindex constants
102 Once that program begins to execute, it uses programmatic allocation to
103 gain additional memory.  In a C program with @theglibc{}, there
104 are two kinds of programmatic allocation: automatic and dynamic.
105 @xref{Memory Allocation and C}.
107 Memory-mapped I/O is another form of dynamic virtual memory allocation.
108 Mapping memory to a file means declaring that the contents of certain
109 range of a process' addresses shall be identical to the contents of a
110 specified regular file.  The system makes the virtual memory initially
111 contain the contents of the file, and if you modify the memory, the
112 system writes the same modification to the file.  Note that due to the
113 magic of virtual memory and page faults, there is no reason for the
114 system to do I/O to read the file, or allocate real memory for its
115 contents, until the program accesses the virtual memory.
116 @xref{Memory-mapped I/O}.
117 @cindex memory mapped I/O
118 @cindex memory mapped file
119 @cindex files, accessing
121 Just as it programmatically allocates memory, the program can
122 programmatically deallocate (@dfn{free}) it.  You can't free the memory
123 that was allocated by exec.  When the program exits or execs, you might
124 say that all its memory gets freed, but since in both cases the address
125 space ceases to exist, the point is really moot.  @xref{Program
126 Termination}.
127 @cindex execing a program
128 @cindex freeing memory
129 @cindex exiting a program
131 A process' virtual address space is divided into segments.  A segment is
132 a contiguous range of virtual addresses.  Three important segments are:
134 @itemize @bullet
136 @item
138 The @dfn{text segment} contains a program's instructions and literals and
139 static constants.  It is allocated by exec and stays the same size for
140 the life of the virtual address space.
142 @item
143 The @dfn{data segment} is working storage for the program.  It can be
144 preallocated and preloaded by exec and the process can extend or shrink
145 it by calling functions as described in @xref{Resizing the Data
146 Segment}.  Its lower end is fixed.
148 @item
149 The @dfn{stack segment} contains a program stack.  It grows as the stack
150 grows, but doesn't shrink when the stack shrinks.
152 @end itemize
156 @node Memory Allocation
157 @section Allocating Storage For Program Data
159 This section covers how ordinary programs manage storage for their data,
160 including the famous @code{malloc} function and some fancier facilities
161 special to @theglibc{} and GNU Compiler.
163 @menu
164 * Memory Allocation and C::     How to get different kinds of allocation in C.
165 * The GNU Allocator::           An overview of the GNU @code{malloc}
166                                 implementation.
167 * Unconstrained Allocation::    The @code{malloc} facility allows fully general
168                                  dynamic allocation.
169 * Allocation Debugging::        Finding memory leaks and not freed memory.
170 * Obstacks::                    Obstacks are less general than malloc
171                                  but more efficient and convenient.
172 * Variable Size Automatic::     Allocation of variable-sized blocks
173                                  of automatic storage that are freed when the
174                                  calling function returns.
175 @end menu
178 @node Memory Allocation and C
179 @subsection Memory Allocation in C Programs
181 The C language supports two kinds of memory allocation through the
182 variables in C programs:
184 @itemize @bullet
185 @item
186 @dfn{Static allocation} is what happens when you declare a static or
187 global variable.  Each static or global variable defines one block of
188 space, of a fixed size.  The space is allocated once, when your program
189 is started (part of the exec operation), and is never freed.
190 @cindex static memory allocation
191 @cindex static storage class
193 @item
194 @dfn{Automatic allocation} happens when you declare an automatic
195 variable, such as a function argument or a local variable.  The space
196 for an automatic variable is allocated when the compound statement
197 containing the declaration is entered, and is freed when that
198 compound statement is exited.
199 @cindex automatic memory allocation
200 @cindex automatic storage class
202 In GNU C, the size of the automatic storage can be an expression
203 that varies.  In other C implementations, it must be a constant.
204 @end itemize
206 A third important kind of memory allocation, @dfn{dynamic allocation},
207 is not supported by C variables but is available via @glibcadj{}
208 functions.
209 @cindex dynamic memory allocation
211 @subsubsection Dynamic Memory Allocation
212 @cindex dynamic memory allocation
214 @dfn{Dynamic memory allocation} is a technique in which programs
215 determine as they are running where to store some information.  You need
216 dynamic allocation when the amount of memory you need, or how long you
217 continue to need it, depends on factors that are not known before the
218 program runs.
220 For example, you may need a block to store a line read from an input
221 file; since there is no limit to how long a line can be, you must
222 allocate the memory dynamically and make it dynamically larger as you
223 read more of the line.
225 Or, you may need a block for each record or each definition in the input
226 data; since you can't know in advance how many there will be, you must
227 allocate a new block for each record or definition as you read it.
229 When you use dynamic allocation, the allocation of a block of memory is
230 an action that the program requests explicitly.  You call a function or
231 macro when you want to allocate space, and specify the size with an
232 argument.  If you want to free the space, you do so by calling another
233 function or macro.  You can do these things whenever you want, as often
234 as you want.
236 Dynamic allocation is not supported by C variables; there is no storage
237 class ``dynamic'', and there can never be a C variable whose value is
238 stored in dynamically allocated space.  The only way to get dynamically
239 allocated memory is via a system call (which is generally via a @glibcadj{}
240 function call), and the only way to refer to dynamically
241 allocated space is through a pointer.  Because it is less convenient,
242 and because the actual process of dynamic allocation requires more
243 computation time, programmers generally use dynamic allocation only when
244 neither static nor automatic allocation will serve.
246 For example, if you want to allocate dynamically some space to hold a
247 @code{struct foobar}, you cannot declare a variable of type @code{struct
248 foobar} whose contents are the dynamically allocated space.  But you can
249 declare a variable of pointer type @code{struct foobar *} and assign it the
250 address of the space.  Then you can use the operators @samp{*} and
251 @samp{->} on this pointer variable to refer to the contents of the space:
253 @smallexample
255   struct foobar *ptr
256      = (struct foobar *) malloc (sizeof (struct foobar));
257   ptr->name = x;
258   ptr->next = current_foobar;
259   current_foobar = ptr;
261 @end smallexample
263 @node The GNU Allocator
264 @subsection The GNU Allocator
265 @cindex gnu allocator
267 The @code{malloc} implementation in @theglibc{} is derived from ptmalloc
268 (pthreads malloc), which in turn is derived from dlmalloc (Doug Lea malloc).
269 This malloc may allocate memory in two different ways depending on their size
270 and certain parameters that may be controlled by users. The most common way is
271 to allocate portions of memory (called chunks) from a large contiguous area of
272 memory and manage these areas to optimize their use and reduce wastage in the
273 form of unusable chunks. Traditionally the system heap was set up to be the one
274 large memory area but the @glibcadj{} @code{malloc} implementation maintains
275 multiple such areas to optimize their use in multi-threaded applications.  Each
276 such area is internally referred to as an @dfn{arena}.
278 As opposed to other versions, the @code{malloc} in @theglibc{} does not round
279 up chunk sizes to powers of two, neither for large nor for small sizes.
280 Neighboring chunks can be coalesced on a @code{free} no matter what their size
281 is.  This makes the implementation suitable for all kinds of allocation
282 patterns without generally incurring high memory waste through fragmentation.
283 The presence of multiple arenas allows multiple threads to allocate
284 memory simultaneously in separate arenas, thus improving performance.
286 The other way of memory allocation is for very large blocks, i.e. much larger
287 than a page. These requests are allocated with @code{mmap} (anonymous or via
288 @file{/dev/zero}; @pxref{Memory-mapped I/O})). This has the great advantage
289 that these chunks are returned to the system immediately when they are freed.
290 Therefore, it cannot happen that a large chunk becomes ``locked'' in between
291 smaller ones and even after calling @code{free} wastes memory.  The size
292 threshold for @code{mmap} to be used is dynamic and gets adjusted according to
293 allocation patterns of the program.  @code{mallopt} can be used to statically
294 adjust the threshold using @code{M_MMAP_THRESHOLD} and the use of @code{mmap}
295 can be disabled completely with @code{M_MMAP_MAX};
296 @pxref{Malloc Tunable Parameters}.
298 A more detailed technical description of the GNU Allocator is maintained in
299 the @glibcadj{} wiki. See
300 @uref{https://sourceware.org/glibc/wiki/MallocInternals}.
302 @node Unconstrained Allocation
303 @subsection Unconstrained Allocation
304 @cindex unconstrained memory allocation
305 @cindex @code{malloc} function
306 @cindex heap, dynamic allocation from
308 The most general dynamic allocation facility is @code{malloc}.  It
309 allows you to allocate blocks of memory of any size at any time, make
310 them bigger or smaller at any time, and free the blocks individually at
311 any time (or never).
313 @menu
314 * Basic Allocation::            Simple use of @code{malloc}.
315 * Malloc Examples::             Examples of @code{malloc}.  @code{xmalloc}.
316 * Freeing after Malloc::        Use @code{free} to free a block you
317                                  got with @code{malloc}.
318 * Changing Block Size::         Use @code{realloc} to make a block
319                                  bigger or smaller.
320 * Allocating Cleared Space::    Use @code{calloc} to allocate a
321                                  block and clear it.
322 * Aligned Memory Blocks::       Allocating specially aligned memory.
323 * Malloc Tunable Parameters::   Use @code{mallopt} to adjust allocation
324                                  parameters.
325 * Heap Consistency Checking::   Automatic checking for errors.
326 * Hooks for Malloc::            You can use these hooks for debugging
327                                  programs that use @code{malloc}.
328 * Statistics of Malloc::        Getting information about how much
329                                  memory your program is using.
330 * Summary of Malloc::           Summary of @code{malloc} and related functions.
331 @end menu
333 @node Basic Allocation
334 @subsubsection Basic Memory Allocation
335 @cindex allocation of memory with @code{malloc}
337 To allocate a block of memory, call @code{malloc}.  The prototype for
338 this function is in @file{stdlib.h}.
339 @pindex stdlib.h
341 @comment malloc.h stdlib.h
342 @comment ISO
343 @deftypefun {void *} malloc (size_t @var{size})
344 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
345 @c Malloc hooks and __morecore pointers, as well as such parameters as
346 @c max_n_mmaps and max_mmapped_mem, are accessed without guards, so they
347 @c could pose a thread safety issue; in order to not declare malloc
348 @c MT-unsafe, it's modifying the hooks and parameters while multiple
349 @c threads are active that is regarded as unsafe.  An arena's next field
350 @c is initialized and never changed again, except for main_arena's,
351 @c that's protected by list_lock; next_free is only modified while
352 @c list_lock is held too.  All other data members of an arena, as well
353 @c as the metadata of the memory areas assigned to it, are only modified
354 @c while holding the arena's mutex (fastbin pointers use catomic ops
355 @c because they may be modified by free without taking the arena's
356 @c lock).  Some reassurance was needed for fastbins, for it wasn't clear
357 @c how they were initialized.  It turns out they are always
358 @c zero-initialized: main_arena's, for being static data, and other
359 @c arena's, for being just-mmapped memory.
361 @c Leaking file descriptors and memory in case of cancellation is
362 @c unavoidable without disabling cancellation, but the lock situation is
363 @c a bit more complicated: we don't have fallback arenas for malloc to
364 @c be safe to call from within signal handlers.  Error-checking mutexes
365 @c or trylock could enable us to try and use alternate arenas, even with
366 @c -DPER_THREAD (enabled by default), but supporting interruption
367 @c (cancellation or signal handling) while holding the arena list mutex
368 @c would require more work; maybe blocking signals and disabling async
369 @c cancellation while manipulating the arena lists?
371 @c __libc_malloc @asulock @aculock @acsfd @acsmem
372 @c  force_reg ok
373 @c  *malloc_hook unguarded
374 @c  arena_lock @asulock @aculock @acsfd @acsmem
375 @c   mutex_lock @asulock @aculock
376 @c   arena_get2 @asulock @aculock @acsfd @acsmem
377 @c    get_free_list @asulock @aculock
378 @c     mutex_lock (list_lock) dup @asulock @aculock
379 @c     mutex_unlock (list_lock) dup @aculock
380 @c     mutex_lock (arena lock) dup @asulock @aculock [returns locked]
381 @c    __get_nprocs ext ok @acsfd
382 @c    NARENAS_FROM_NCORES ok
383 @c    catomic_compare_and_exchange_bool_acq ok
384 @c    _int_new_arena ok @asulock @aculock @acsmem
385 @c     new_heap ok @acsmem
386 @c      mmap ok @acsmem
387 @c      munmap ok @acsmem
388 @c      mprotect ok
389 @c     chunk2mem ok
390 @c     set_head ok
391 @c     tsd_setspecific dup ok
392 @c     mutex_init ok
393 @c     mutex_lock (just-created mutex) ok, returns locked
394 @c     mutex_lock (list_lock) dup @asulock @aculock
395 @c     atomic_write_barrier ok
396 @c     mutex_unlock (list_lock) @aculock
397 @c    catomic_decrement ok
398 @c    reused_arena @asulock @aculock
399 @c      reads&writes next_to_use and iterates over arena next without guards
400 @c      those are harmless as long as we don't drop arenas from the
401 @c      NEXT list, and we never do; when a thread terminates,
402 @c      arena_thread_freeres prepends the arena to the free_list
403 @c      NEXT_FREE list, but NEXT is never modified, so it's safe!
404 @c     mutex_trylock (arena lock) @asulock @aculock
405 @c     mutex_lock (arena lock) dup @asulock @aculock
406 @c     tsd_setspecific dup ok
407 @c  _int_malloc @acsfd @acsmem
408 @c   checked_request2size ok
409 @c    REQUEST_OUT_OF_RANGE ok
410 @c    request2size ok
411 @c   get_max_fast ok
412 @c   fastbin_index ok
413 @c   fastbin ok
414 @c   catomic_compare_and_exhange_val_acq ok
415 @c   malloc_printerr dup @mtsenv
416 @c     if we get to it, we're toast already, undefined behavior must have
417 @c     been invoked before
418 @c    libc_message @mtsenv [no leaks with cancellation disabled]
419 @c     FATAL_PREPARE ok
420 @c      pthread_setcancelstate disable ok
421 @c     libc_secure_getenv @mtsenv
422 @c      getenv @mtsenv
423 @c     open_not_cancel_2 dup @acsfd
424 @c     strchrnul ok
425 @c     WRITEV_FOR_FATAL ok
426 @c      writev ok
427 @c     mmap ok @acsmem
428 @c     munmap ok @acsmem
429 @c     BEFORE_ABORT @acsfd
430 @c      backtrace ok
431 @c      write_not_cancel dup ok
432 @c      backtrace_symbols_fd @aculock
433 @c      open_not_cancel_2 dup @acsfd
434 @c      read_not_cancel dup ok
435 @c      close_not_cancel_no_status dup @acsfd
436 @c     abort ok
437 @c    itoa_word ok
438 @c    abort ok
439 @c   check_remalloced_chunk ok/disabled
440 @c   chunk2mem dup ok
441 @c   alloc_perturb ok
442 @c   in_smallbin_range ok
443 @c   smallbin_index ok
444 @c   bin_at ok
445 @c   last ok
446 @c   malloc_consolidate ok
447 @c    get_max_fast dup ok
448 @c    clear_fastchunks ok
449 @c    unsorted_chunks dup ok
450 @c    fastbin dup ok
451 @c    atomic_exchange_acq ok
452 @c    check_inuse_chunk dup ok/disabled
453 @c    chunk_at_offset dup ok
454 @c    chunksize dup ok
455 @c    inuse_bit_at_offset dup ok
456 @c    unlink dup ok
457 @c    clear_inuse_bit_at_offset dup ok
458 @c    in_smallbin_range dup ok
459 @c    set_head dup ok
460 @c    malloc_init_state ok
461 @c     bin_at dup ok
462 @c     set_noncontiguous dup ok
463 @c     set_max_fast dup ok
464 @c     initial_top ok
465 @c      unsorted_chunks dup ok
466 @c    check_malloc_state ok/disabled
467 @c   set_inuse_bit_at_offset ok
468 @c   check_malloced_chunk ok/disabled
469 @c   largebin_index ok
470 @c   have_fastchunks ok
471 @c   unsorted_chunks ok
472 @c    bin_at ok
473 @c   chunksize ok
474 @c   chunk_at_offset ok
475 @c   set_head ok
476 @c   set_foot ok
477 @c   mark_bin ok
478 @c    idx2bit ok
479 @c   first ok
480 @c   unlink ok
481 @c    malloc_printerr dup ok
482 @c    in_smallbin_range dup ok
483 @c   idx2block ok
484 @c   idx2bit dup ok
485 @c   next_bin ok
486 @c   sysmalloc @acsfd @acsmem
487 @c    MMAP @acsmem
488 @c    set_head dup ok
489 @c    check_chunk ok/disabled
490 @c    chunk2mem dup ok
491 @c    chunksize dup ok
492 @c    chunk_at_offset dup ok
493 @c    heap_for_ptr ok
494 @c    grow_heap ok
495 @c     mprotect ok
496 @c    set_head dup ok
497 @c    new_heap @acsmem
498 @c     MMAP dup @acsmem
499 @c     munmap @acsmem
500 @c    top ok
501 @c    set_foot dup ok
502 @c    contiguous ok
503 @c    MORECORE ok
504 @c     *__morecore ok unguarded
505 @c      __default_morecore
506 @c       sbrk ok
507 @c    force_reg dup ok
508 @c    *__after_morecore_hook unguarded
509 @c    set_noncontiguous ok
510 @c    malloc_printerr dup ok
511 @c    _int_free (have_lock) @acsfd @acsmem [@asulock @aculock]
512 @c     chunksize dup ok
513 @c     mutex_unlock dup @aculock/!have_lock
514 @c     malloc_printerr dup ok
515 @c     check_inuse_chunk ok/disabled
516 @c     chunk_at_offset dup ok
517 @c     mutex_lock dup @asulock @aculock/@have_lock
518 @c     chunk2mem dup ok
519 @c     free_perturb ok
520 @c     set_fastchunks ok
521 @c      catomic_and ok
522 @c     fastbin_index dup ok
523 @c     fastbin dup ok
524 @c     catomic_compare_and_exchange_val_rel ok
525 @c     chunk_is_mmapped ok
526 @c     contiguous dup ok
527 @c     prev_inuse ok
528 @c     unlink dup ok
529 @c     inuse_bit_at_offset dup ok
530 @c     clear_inuse_bit_at_offset ok
531 @c     unsorted_chunks dup ok
532 @c     in_smallbin_range dup ok
533 @c     set_head dup ok
534 @c     set_foot dup ok
535 @c     check_free_chunk ok/disabled
536 @c     check_chunk dup ok/disabled
537 @c     have_fastchunks dup ok
538 @c     malloc_consolidate dup ok
539 @c     systrim ok
540 @c      MORECORE dup ok
541 @c      *__after_morecore_hook dup unguarded
542 @c      set_head dup ok
543 @c      check_malloc_state ok/disabled
544 @c     top dup ok
545 @c     heap_for_ptr dup ok
546 @c     heap_trim @acsfd @acsmem
547 @c      top dup ok
548 @c      chunk_at_offset dup ok
549 @c      prev_chunk ok
550 @c      chunksize dup ok
551 @c      prev_inuse dup ok
552 @c      delete_heap @acsmem
553 @c       munmap dup @acsmem
554 @c      unlink dup ok
555 @c      set_head dup ok
556 @c      shrink_heap @acsfd
557 @c       check_may_shrink_heap @acsfd
558 @c        open_not_cancel_2 @acsfd
559 @c        read_not_cancel ok
560 @c        close_not_cancel_no_status @acsfd
561 @c       MMAP dup ok
562 @c       madvise ok
563 @c     munmap_chunk @acsmem
564 @c      chunksize dup ok
565 @c      chunk_is_mmapped dup ok
566 @c      chunk2mem dup ok
567 @c      malloc_printerr dup ok
568 @c      munmap dup @acsmem
569 @c    check_malloc_state ok/disabled
570 @c  arena_get_retry @asulock @aculock @acsfd @acsmem
571 @c   mutex_unlock dup @aculock
572 @c   mutex_lock dup @asulock @aculock
573 @c   arena_get2 dup @asulock @aculock @acsfd @acsmem
574 @c  mutex_unlock @aculock
575 @c  mem2chunk ok
576 @c  chunk_is_mmapped ok
577 @c  arena_for_chunk ok
578 @c   chunk_non_main_arena ok
579 @c   heap_for_ptr ok
580 This function returns a pointer to a newly allocated block @var{size}
581 bytes long, or a null pointer if the block could not be allocated.
582 @end deftypefun
584 The contents of the block are undefined; you must initialize it yourself
585 (or use @code{calloc} instead; @pxref{Allocating Cleared Space}).
586 Normally you would cast the value as a pointer to the kind of object
587 that you want to store in the block.  Here we show an example of doing
588 so, and of initializing the space with zeros using the library function
589 @code{memset} (@pxref{Copying Strings and Arrays}):
591 @smallexample
592 struct foo *ptr;
593 @dots{}
594 ptr = (struct foo *) malloc (sizeof (struct foo));
595 if (ptr == 0) abort ();
596 memset (ptr, 0, sizeof (struct foo));
597 @end smallexample
599 You can store the result of @code{malloc} into any pointer variable
600 without a cast, because @w{ISO C} automatically converts the type
601 @code{void *} to another type of pointer when necessary.  But the cast
602 is necessary in contexts other than assignment operators or if you might
603 want your code to run in traditional C.
605 Remember that when allocating space for a string, the argument to
606 @code{malloc} must be one plus the length of the string.  This is
607 because a string is terminated with a null character that doesn't count
608 in the ``length'' of the string but does need space.  For example:
610 @smallexample
611 char *ptr;
612 @dots{}
613 ptr = (char *) malloc (length + 1);
614 @end smallexample
616 @noindent
617 @xref{Representation of Strings}, for more information about this.
619 @node Malloc Examples
620 @subsubsection Examples of @code{malloc}
622 If no more space is available, @code{malloc} returns a null pointer.
623 You should check the value of @emph{every} call to @code{malloc}.  It is
624 useful to write a subroutine that calls @code{malloc} and reports an
625 error if the value is a null pointer, returning only if the value is
626 nonzero.  This function is conventionally called @code{xmalloc}.  Here
627 it is:
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 = (char *) xmalloc (len + 1);
650   value[len] = '\0';
651   return (char *) 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 @node Freeing after Malloc
673 @subsubsection Freeing Memory Allocated with @code{malloc}
674 @cindex freeing memory allocated with @code{malloc}
675 @cindex heap, freeing memory from
677 When you no longer need a block that you got with @code{malloc}, use the
678 function @code{free} to make the block available to be allocated again.
679 The prototype for this function is in @file{stdlib.h}.
680 @pindex stdlib.h
682 @comment malloc.h stdlib.h
683 @comment ISO
684 @deftypefun void free (void *@var{ptr})
685 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
686 @c __libc_free @asulock @aculock @acsfd @acsmem
687 @c   releasing memory into fastbins modifies the arena without taking
688 @c   its mutex, but catomic operations ensure safety.  If two (or more)
689 @c   threads are running malloc and have their own arenas locked when
690 @c   each gets a signal whose handler free()s large (non-fastbin-able)
691 @c   blocks from each other's arena, we deadlock; this is a more general
692 @c   case of @asulock.
693 @c  *__free_hook unguarded
694 @c  mem2chunk ok
695 @c  chunk_is_mmapped ok, chunk bits not modified after allocation
696 @c  chunksize ok
697 @c  munmap_chunk dup @acsmem
698 @c  arena_for_chunk dup ok
699 @c  _int_free (!have_lock) dup @asulock @aculock @acsfd @acsmem
700 The @code{free} function deallocates the block of memory pointed at
701 by @var{ptr}.
702 @end deftypefun
704 @comment stdlib.h
705 @comment Sun
706 @deftypefun void cfree (void *@var{ptr})
707 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
708 @c alias to free
709 This function does the same thing as @code{free}.  It's provided for
710 backward compatibility with SunOS; you should use @code{free} instead.
711 @end deftypefun
713 Freeing a block alters the contents of the block.  @strong{Do not expect to
714 find any data (such as a pointer to the next block in a chain of blocks) in
715 the block after freeing it.}  Copy whatever you need out of the block before
716 freeing it!  Here is an example of the proper way to free all the blocks in
717 a chain, and the strings that they point to:
719 @smallexample
720 struct chain
721   @{
722     struct chain *next;
723     char *name;
724   @}
726 void
727 free_chain (struct chain *chain)
729   while (chain != 0)
730     @{
731       struct chain *next = chain->next;
732       free (chain->name);
733       free (chain);
734       chain = next;
735     @}
737 @end smallexample
739 Occasionally, @code{free} can actually return memory to the operating
740 system and make the process smaller.  Usually, all it can do is allow a
741 later call to @code{malloc} to reuse the space.  In the meantime, the
742 space remains in your program as part of a free-list used internally by
743 @code{malloc}.
745 There is no point in freeing blocks at the end of a program, because all
746 of the program's space is given back to the system when the process
747 terminates.
749 @node Changing Block Size
750 @subsubsection Changing the Size of a Block
751 @cindex changing the size of a block (@code{malloc})
753 Often you do not know for certain how big a block you will ultimately need
754 at the time you must begin to use the block.  For example, the block might
755 be a buffer that you use to hold a line being read from a file; no matter
756 how long you make the buffer initially, you may encounter a line that is
757 longer.
759 You can make the block longer by calling @code{realloc}.  This function
760 is declared in @file{stdlib.h}.
761 @pindex stdlib.h
763 @comment malloc.h stdlib.h
764 @comment ISO
765 @deftypefun {void *} realloc (void *@var{ptr}, size_t @var{newsize})
766 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
767 @c It may call the implementations of malloc and free, so all of their
768 @c issues arise, plus the realloc hook, also accessed without guards.
770 @c __libc_realloc @asulock @aculock @acsfd @acsmem
771 @c  *__realloc_hook unguarded
772 @c  __libc_free dup @asulock @aculock @acsfd @acsmem
773 @c  __libc_malloc dup @asulock @aculock @acsfd @acsmem
774 @c  mem2chunk dup ok
775 @c  chunksize dup ok
776 @c  malloc_printerr dup ok
777 @c  checked_request2size dup ok
778 @c  chunk_is_mmapped dup ok
779 @c  mremap_chunk
780 @c   chunksize dup ok
781 @c   __mremap ok
782 @c   set_head dup ok
783 @c  MALLOC_COPY ok
784 @c   memcpy ok
785 @c  munmap_chunk dup @acsmem
786 @c  arena_for_chunk dup ok
787 @c  mutex_lock (arena mutex) dup @asulock @aculock
788 @c  _int_realloc @acsfd @acsmem
789 @c   malloc_printerr dup ok
790 @c   check_inuse_chunk dup ok/disabled
791 @c   chunk_at_offset dup ok
792 @c   chunksize dup ok
793 @c   set_head_size dup ok
794 @c   chunk_at_offset dup ok
795 @c   set_head dup ok
796 @c   chunk2mem dup ok
797 @c   inuse dup ok
798 @c   unlink dup ok
799 @c   _int_malloc dup @acsfd @acsmem
800 @c   mem2chunk dup ok
801 @c   MALLOC_COPY dup ok
802 @c   _int_free (have_lock) dup @acsfd @acsmem
803 @c   set_inuse_bit_at_offset dup ok
804 @c   set_head dup ok
805 @c  mutex_unlock (arena mutex) dup @aculock
806 @c  _int_free (!have_lock) dup @asulock @aculock @acsfd @acsmem
808 The @code{realloc} function changes the size of the block whose address is
809 @var{ptr} to be @var{newsize}.
811 Since the space after the end of the block may be in use, @code{realloc}
812 may find it necessary to copy the block to a new address where more free
813 space is available.  The value of @code{realloc} is the new address of the
814 block.  If the block needs to be moved, @code{realloc} copies the old
815 contents.
817 If you pass a null pointer for @var{ptr}, @code{realloc} behaves just
818 like @samp{malloc (@var{newsize})}.  This can be convenient, but beware
819 that older implementations (before @w{ISO C}) may not support this
820 behavior, and will probably crash when @code{realloc} is passed a null
821 pointer.
822 @end deftypefun
824 Like @code{malloc}, @code{realloc} may return a null pointer if no
825 memory space is available to make the block bigger.  When this happens,
826 the original block is untouched; it has not been modified or relocated.
828 In most cases it makes no difference what happens to the original block
829 when @code{realloc} fails, because the application program cannot continue
830 when it is out of memory, and the only thing to do is to give a fatal error
831 message.  Often it is convenient to write and use a subroutine,
832 conventionally called @code{xrealloc}, that takes care of the error message
833 as @code{xmalloc} does for @code{malloc}:
835 @smallexample
836 void *
837 xrealloc (void *ptr, size_t size)
839   void *value = realloc (ptr, size);
840   if (value == 0)
841     fatal ("Virtual memory exhausted");
842   return value;
844 @end smallexample
846 You can also use @code{realloc} to make a block smaller.  The reason you
847 would do this is to avoid tying up a lot of memory space when only a little
848 is needed.
849 @comment The following is no longer true with the new malloc.
850 @comment But it seems wise to keep the warning for other implementations.
851 In several allocation implementations, making a block smaller sometimes
852 necessitates copying it, so it can fail if no other space is available.
854 If the new size you specify is the same as the old size, @code{realloc}
855 is guaranteed to change nothing and return the same address that you gave.
857 @node Allocating Cleared Space
858 @subsubsection Allocating Cleared Space
860 The function @code{calloc} allocates memory and clears it to zero.  It
861 is declared in @file{stdlib.h}.
862 @pindex stdlib.h
864 @comment malloc.h stdlib.h
865 @comment ISO
866 @deftypefun {void *} calloc (size_t @var{count}, size_t @var{eltsize})
867 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
868 @c Same caveats as malloc.
870 @c __libc_calloc @asulock @aculock @acsfd @acsmem
871 @c  *__malloc_hook dup unguarded
872 @c  memset dup ok
873 @c  arena_get @asulock @aculock @acsfd @acsmem
874 @c   arena_lock dup @asulock @aculock @acsfd @acsmem
875 @c  top dup ok
876 @c  chunksize dup ok
877 @c  heap_for_ptr dup ok
878 @c  _int_malloc dup @acsfd @acsmem
879 @c  arena_get_retry dup @asulock @aculock @acsfd @acsmem
880 @c  mutex_unlock dup @aculock
881 @c  mem2chunk dup ok
882 @c  chunk_is_mmapped dup ok
883 @c  MALLOC_ZERO ok
884 @c   memset dup ok
885 This function allocates a block long enough to contain a vector of
886 @var{count} elements, each of size @var{eltsize}.  Its contents are
887 cleared to zero before @code{calloc} returns.
888 @end deftypefun
890 You could define @code{calloc} as follows:
892 @smallexample
893 void *
894 calloc (size_t count, size_t eltsize)
896   size_t size = count * eltsize;
897   void *value = malloc (size);
898   if (value != 0)
899     memset (value, 0, size);
900   return value;
902 @end smallexample
904 But in general, it is not guaranteed that @code{calloc} calls
905 @code{malloc} internally.  Therefore, if an application provides its own
906 @code{malloc}/@code{realloc}/@code{free} outside the C library, it
907 should always define @code{calloc}, too.
909 @node Aligned Memory Blocks
910 @subsubsection Allocating Aligned Memory Blocks
912 @cindex page boundary
913 @cindex alignment (with @code{malloc})
914 @pindex stdlib.h
915 The address of a block returned by @code{malloc} or @code{realloc} in
916 @gnusystems{} is always a multiple of eight (or sixteen on 64-bit
917 systems).  If you need a block whose address is a multiple of a higher
918 power of two than that, use @code{aligned_alloc} or @code{posix_memalign}.
919 @code{aligned_alloc} and @code{posix_memalign} are declared in
920 @file{stdlib.h}.
922 @comment stdlib.h
923 @deftypefun {void *} aligned_alloc (size_t @var{alignment}, size_t @var{size})
924 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
925 @c Alias to memalign.
926 The @code{aligned_alloc} function allocates a block of @var{size} bytes whose
927 address is a multiple of @var{alignment}.  The @var{alignment} must be a
928 power of two and @var{size} must be a multiple of @var{alignment}.
930 The @code{aligned_alloc} function returns a null pointer on error and sets
931 @code{errno} to one of the following values:
933 @table @code
934 @item ENOMEM
935 There was insufficient memory available to satisfy the request.
937 @item EINVAL
938 @var{alignment} is not a power of two.
940 This function was introduced in @w{ISO C11} and hence may have better
941 portability to modern non-POSIX systems than @code{posix_memalign}.
942 @end table
944 @end deftypefun
946 @comment malloc.h
947 @comment BSD
948 @deftypefun {void *} memalign (size_t @var{boundary}, size_t @var{size})
949 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
950 @c Same issues as malloc.  The padding bytes are safely freed in
951 @c _int_memalign, with the arena still locked.
953 @c __libc_memalign @asulock @aculock @acsfd @acsmem
954 @c  *__memalign_hook dup unguarded
955 @c  __libc_malloc dup @asulock @aculock @acsfd @acsmem
956 @c  arena_get dup @asulock @aculock @acsfd @acsmem
957 @c  _int_memalign @acsfd @acsmem
958 @c   _int_malloc dup @acsfd @acsmem
959 @c   checked_request2size dup ok
960 @c   mem2chunk dup ok
961 @c   chunksize dup ok
962 @c   chunk_is_mmapped dup ok
963 @c   set_head dup ok
964 @c   chunk2mem dup ok
965 @c   set_inuse_bit_at_offset dup ok
966 @c   set_head_size dup ok
967 @c   _int_free (have_lock) dup @acsfd @acsmem
968 @c   chunk_at_offset dup ok
969 @c   check_inuse_chunk dup ok
970 @c  arena_get_retry dup @asulock @aculock @acsfd @acsmem
971 @c  mutex_unlock dup @aculock
972 The @code{memalign} function allocates a block of @var{size} bytes whose
973 address is a multiple of @var{boundary}.  The @var{boundary} must be a
974 power of two!  The function @code{memalign} works by allocating a
975 somewhat larger block, and then returning an address within the block
976 that is on the specified boundary.
978 The @code{memalign} function returns a null pointer on error and sets
979 @code{errno} to one of the following values:
981 @table @code
982 @item ENOMEM
983 There was insufficient memory available to satisfy the request.
985 @item EINVAL
986 @var{boundary} is not a power of two.
988 @end table
990 The @code{memalign} function is obsolete and @code{aligned_alloc} or
991 @code{posix_memalign} should be used instead.
992 @end deftypefun
994 @comment stdlib.h
995 @comment POSIX
996 @deftypefun int posix_memalign (void **@var{memptr}, size_t @var{alignment}, size_t @var{size})
997 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
998 @c Calls memalign unless the requirements are not met (powerof2 macro is
999 @c safe given an automatic variable as an argument) or there's a
1000 @c memalign hook (accessed unguarded, but safely).
1001 The @code{posix_memalign} function is similar to the @code{memalign}
1002 function in that it returns a buffer of @var{size} bytes aligned to a
1003 multiple of @var{alignment}.  But it adds one requirement to the
1004 parameter @var{alignment}: the value must be a power of two multiple of
1005 @code{sizeof (void *)}.
1007 If the function succeeds in allocation memory a pointer to the allocated
1008 memory is returned in @code{*@var{memptr}} and the return value is zero.
1009 Otherwise the function returns an error value indicating the problem.
1010 The possible error values returned are:
1012 @table @code
1013 @item ENOMEM
1014 There was insufficient memory available to satisfy the request.
1016 @item EINVAL
1017 @var{alignment} is not a power of two multiple of @code{sizeof (void *)}.
1019 @end table
1021 This function was introduced in POSIX 1003.1d.  Although this function is
1022 superseded by @code{aligned_alloc}, it is more portable to older POSIX
1023 systems that do not support @w{ISO C11}.
1024 @end deftypefun
1026 @comment malloc.h stdlib.h
1027 @comment BSD
1028 @deftypefun {void *} valloc (size_t @var{size})
1029 @safety{@prelim{}@mtunsafe{@mtuinit{}}@asunsafe{@asuinit{} @asulock{}}@acunsafe{@acuinit{} @aculock{} @acsfd{} @acsmem{}}}
1030 @c __libc_valloc @mtuinit @asuinit @asulock @aculock @acsfd @acsmem
1031 @c  ptmalloc_init (once) @mtsenv @asulock @aculock @acsfd @acsmem
1032 @c   _dl_addr @asucorrupt? @aculock
1033 @c    __rtld_lock_lock_recursive (dl_load_lock) @asucorrupt? @aculock
1034 @c    _dl_find_dso_for_object ok, iterates over dl_ns and its _ns_loaded objs
1035 @c      the ok above assumes no partial updates on dl_ns and _ns_loaded
1036 @c      that could confuse a _dl_addr call in a signal handler
1037 @c     _dl_addr_inside_object ok
1038 @c    determine_info ok
1039 @c    __rtld_lock_unlock_recursive (dl_load_lock) @aculock
1040 @c   *_environ @mtsenv
1041 @c   next_env_entry ok
1042 @c   strcspn dup ok
1043 @c   __libc_mallopt dup @mtasuconst:mallopt [setting mp_]
1044 @c   __malloc_check_init @mtasuconst:malloc_hooks [setting hooks]
1045 @c   *__malloc_initialize_hook unguarded, ok
1046 @c  *__memalign_hook dup ok, unguarded
1047 @c  arena_get dup @asulock @aculock @acsfd @acsmem
1048 @c  _int_valloc @acsfd @acsmem
1049 @c   malloc_consolidate dup ok
1050 @c   _int_memalign dup @acsfd @acsmem
1051 @c  arena_get_retry dup @asulock @aculock @acsfd @acsmem
1052 @c  _int_memalign dup @acsfd @acsmem
1053 @c  mutex_unlock dup @aculock
1054 Using @code{valloc} is like using @code{memalign} and passing the page size
1055 as the value of the first argument.  It is implemented like this:
1057 @smallexample
1058 void *
1059 valloc (size_t size)
1061   return memalign (getpagesize (), size);
1063 @end smallexample
1065 @ref{Query Memory Parameters} for more information about the memory
1066 subsystem.
1068 The @code{valloc} function is obsolete and @code{aligned_alloc} or
1069 @code{posix_memalign} should be used instead.
1070 @end deftypefun
1072 @node Malloc Tunable Parameters
1073 @subsubsection Malloc Tunable Parameters
1075 You can adjust some parameters for dynamic memory allocation with the
1076 @code{mallopt} function.  This function is the general SVID/XPG
1077 interface, defined in @file{malloc.h}.
1078 @pindex malloc.h
1080 @deftypefun int mallopt (int @var{param}, int @var{value})
1081 @safety{@prelim{}@mtunsafe{@mtuinit{} @mtasuconst{:mallopt}}@asunsafe{@asuinit{} @asulock{}}@acunsafe{@acuinit{} @aculock{}}}
1082 @c __libc_mallopt @mtuinit @mtasuconst:mallopt @asuinit @asulock @aculock
1083 @c  ptmalloc_init (once) dup @mtsenv @asulock @aculock @acsfd @acsmem
1084 @c  mutex_lock (main_arena->mutex) @asulock @aculock
1085 @c  malloc_consolidate dup ok
1086 @c  set_max_fast ok
1087 @c  mutex_unlock dup @aculock
1089 When calling @code{mallopt}, the @var{param} argument specifies the
1090 parameter to be set, and @var{value} the new value to be set.  Possible
1091 choices for @var{param}, as defined in @file{malloc.h}, are:
1093 @comment TODO: @item M_CHECK_ACTION
1094 @vtable @code
1095 @item M_MMAP_MAX
1096 The maximum number of chunks to allocate with @code{mmap}.  Setting this
1097 to zero disables all use of @code{mmap}.
1099 The default value of this parameter is @code{65536}.
1101 This parameter can also be set for the process at startup by setting the
1102 environment variable @env{MALLOC_MMAP_MAX_} to the desired value.
1104 @item M_MMAP_THRESHOLD
1105 All chunks larger than this value are allocated outside the normal
1106 heap, using the @code{mmap} system call.  This way it is guaranteed
1107 that the memory for these chunks can be returned to the system on
1108 @code{free}.  Note that requests smaller than this threshold might still
1109 be allocated via @code{mmap}.
1111 If this parameter is not set, the default value is set as 128 KiB and the
1112 threshold is adjusted dynamically to suit the allocation patterns of the
1113 program. If the parameter is set, the dynamic adjustment is disabled and the
1114 value is set statically to the input value.
1116 This parameter can also be set for the process at startup by setting the
1117 environment variable @env{MALLOC_MMAP_THRESHOLD_} to the desired value.
1118 @comment TODO: @item M_MXFAST
1120 @item M_PERTURB
1121 If non-zero, memory blocks are filled with values depending on some
1122 low order bits of this parameter when they are allocated (except when
1123 allocated by @code{calloc}) and freed.  This can be used to debug the
1124 use of uninitialized or freed heap memory.  Note that this option does not
1125 guarantee that the freed block will have any specific values.  It only
1126 guarantees that the content the block had before it was freed will be
1127 overwritten.
1129 The default value of this parameter is @code{0}.
1131 This parameter can also be set for the process at startup by setting the
1132 environment variable @env{MALLOC_MMAP_PERTURB_} to the desired value.
1134 @item M_TOP_PAD
1135 This parameter determines the amount of extra memory to obtain from the system
1136 when an arena needs to be extended.  It also specifies the number of bytes to
1137 retain when shrinking an arena.  This provides the necessary hysteresis in heap
1138 size such that excessive amounts of system calls can be avoided.
1140 The default value of this parameter is @code{0}.
1142 This parameter can also be set for the process at startup by setting the
1143 environment variable @env{MALLOC_TOP_PAD_} to the desired value.
1145 @item M_TRIM_THRESHOLD
1146 This is the minimum size (in bytes) of the top-most, releasable chunk
1147 that will trigger a system call in order to return memory to the system.
1149 If this parameter is not set, the default value is set as 128 KiB and the
1150 threshold is adjusted dynamically to suit the allocation patterns of the
1151 program. If the parameter is set, the dynamic adjustment is disabled and the
1152 value is set statically to the provided input.
1154 This parameter can also be set for the process at startup by setting the
1155 environment variable @env{MALLOC_TRIM_THRESHOLD_} to the desired value.
1157 @item M_ARENA_TEST
1158 This parameter specifies the number of arenas that can be created before the
1159 test on the limit to the number of arenas is conducted. The value is ignored if
1160 @code{M_ARENA_MAX} is set.
1162 The default value of this parameter is 2 on 32-bit systems and 8 on 64-bit
1163 systems.
1165 This parameter can also be set for the process at startup by setting the
1166 environment variable @env{MALLOC_ARENA_TEST} to the desired value.
1168 @item M_ARENA_MAX
1169 This parameter sets the number of arenas to use regardless of the number of
1170 cores in the system.
1172 The default value of this tunable is @code{0}, meaning that the limit on the
1173 number of arenas is determined by the number of CPU cores online. For 32-bit
1174 systems the limit is twice the number of cores online and on 64-bit systems, it
1175 is eight times the number of cores online.  Note that the default value is not
1176 derived from the default value of M_ARENA_TEST and is computed independently.
1178 This parameter can also be set for the process at startup by setting the
1179 environment variable @env{MALLOC_ARENA_MAX} to the desired value.
1180 @end vtable
1182 @end deftypefun
1184 @node Heap Consistency Checking
1185 @subsubsection Heap Consistency Checking
1187 @cindex heap consistency checking
1188 @cindex consistency checking, of heap
1190 You can ask @code{malloc} to check the consistency of dynamic memory by
1191 using the @code{mcheck} function.  This function is a GNU extension,
1192 declared in @file{mcheck.h}.
1193 @pindex mcheck.h
1195 @comment mcheck.h
1196 @comment GNU
1197 @deftypefun int mcheck (void (*@var{abortfn}) (enum mcheck_status @var{status}))
1198 @safety{@prelim{}@mtunsafe{@mtasurace{:mcheck} @mtasuconst{:malloc_hooks}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
1199 @c The hooks must be set up before malloc is first used, which sort of
1200 @c implies @mtuinit/@asuinit but since the function is a no-op if malloc
1201 @c was already used, that doesn't pose any safety issues.  The actual
1202 @c problem is with the hooks, designed for single-threaded
1203 @c fully-synchronous operation: they manage an unguarded linked list of
1204 @c allocated blocks, and get temporarily overwritten before calling the
1205 @c allocation functions recursively while holding the old hooks.  There
1206 @c are no guards for thread safety, and inconsistent hooks may be found
1207 @c within signal handlers or left behind in case of cancellation.
1209 Calling @code{mcheck} tells @code{malloc} to perform occasional
1210 consistency checks.  These will catch things such as writing
1211 past the end of a block that was allocated with @code{malloc}.
1213 The @var{abortfn} argument is the function to call when an inconsistency
1214 is found.  If you supply a null pointer, then @code{mcheck} uses a
1215 default function which prints a message and calls @code{abort}
1216 (@pxref{Aborting a Program}).  The function you supply is called with
1217 one argument, which says what sort of inconsistency was detected; its
1218 type is described below.
1220 It is too late to begin allocation checking once you have allocated
1221 anything with @code{malloc}.  So @code{mcheck} does nothing in that
1222 case.  The function returns @code{-1} if you call it too late, and
1223 @code{0} otherwise (when it is successful).
1225 The easiest way to arrange to call @code{mcheck} early enough is to use
1226 the option @samp{-lmcheck} when you link your program; then you don't
1227 need to modify your program source at all.  Alternatively you might use
1228 a debugger to insert a call to @code{mcheck} whenever the program is
1229 started, for example these gdb commands will automatically call @code{mcheck}
1230 whenever the program starts:
1232 @smallexample
1233 (gdb) break main
1234 Breakpoint 1, main (argc=2, argv=0xbffff964) at whatever.c:10
1235 (gdb) command 1
1236 Type commands for when breakpoint 1 is hit, one per line.
1237 End with a line saying just "end".
1238 >call mcheck(0)
1239 >continue
1240 >end
1241 (gdb) @dots{}
1242 @end smallexample
1244 This will however only work if no initialization function of any object
1245 involved calls any of the @code{malloc} functions since @code{mcheck}
1246 must be called before the first such function.
1248 @end deftypefun
1250 @deftypefun {enum mcheck_status} mprobe (void *@var{pointer})
1251 @safety{@prelim{}@mtunsafe{@mtasurace{:mcheck} @mtasuconst{:malloc_hooks}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
1252 @c The linked list of headers may be modified concurrently by other
1253 @c threads, and it may find a partial update if called from a signal
1254 @c handler.  It's mostly read only, so cancelling it might be safe, but
1255 @c it will modify global state that, if cancellation hits at just the
1256 @c right spot, may be left behind inconsistent.  This path is only taken
1257 @c if checkhdr finds an inconsistency.  If the inconsistency could only
1258 @c occur because of earlier undefined behavior, that wouldn't be an
1259 @c additional safety issue problem, but because of the other concurrency
1260 @c issues in the mcheck hooks, the apparent inconsistency could be the
1261 @c result of mcheck's own internal data race.  So, AC-Unsafe it is.
1263 The @code{mprobe} function lets you explicitly check for inconsistencies
1264 in a particular allocated block.  You must have already called
1265 @code{mcheck} at the beginning of the program, to do its occasional
1266 checks; calling @code{mprobe} requests an additional consistency check
1267 to be done at the time of the call.
1269 The argument @var{pointer} must be a pointer returned by @code{malloc}
1270 or @code{realloc}.  @code{mprobe} returns a value that says what
1271 inconsistency, if any, was found.  The values are described below.
1272 @end deftypefun
1274 @deftp {Data Type} {enum mcheck_status}
1275 This enumerated type describes what kind of inconsistency was detected
1276 in an allocated block, if any.  Here are the possible values:
1278 @table @code
1279 @item MCHECK_DISABLED
1280 @code{mcheck} was not called before the first allocation.
1281 No consistency checking can be done.
1282 @item MCHECK_OK
1283 No inconsistency detected.
1284 @item MCHECK_HEAD
1285 The data immediately before the block was modified.
1286 This commonly happens when an array index or pointer
1287 is decremented too far.
1288 @item MCHECK_TAIL
1289 The data immediately after the block was modified.
1290 This commonly happens when an array index or pointer
1291 is incremented too far.
1292 @item MCHECK_FREE
1293 The block was already freed.
1294 @end table
1295 @end deftp
1297 Another possibility to check for and guard against bugs in the use of
1298 @code{malloc}, @code{realloc} and @code{free} is to set the environment
1299 variable @code{MALLOC_CHECK_}.  When @code{MALLOC_CHECK_} is set, a
1300 special (less efficient) implementation is used which is designed to be
1301 tolerant against simple errors, such as double calls of @code{free} with
1302 the same argument, or overruns of a single byte (off-by-one bugs).  Not
1303 all such errors can be protected against, however, and memory leaks can
1304 result.  If @code{MALLOC_CHECK_} is set to @code{0}, any detected heap
1305 corruption is silently ignored; if set to @code{1}, a diagnostic is
1306 printed on @code{stderr}; if set to @code{2}, @code{abort} is called
1307 immediately.  This can be useful because otherwise a crash may happen
1308 much later, and the true cause for the problem is then very hard to
1309 track down.
1311 There is one problem with @code{MALLOC_CHECK_}: in SUID or SGID binaries
1312 it could possibly be exploited since diverging from the normal programs
1313 behavior it now writes something to the standard error descriptor.
1314 Therefore the use of @code{MALLOC_CHECK_} is disabled by default for
1315 SUID and SGID binaries.  It can be enabled again by the system
1316 administrator by adding a file @file{/etc/suid-debug} (the content is
1317 not important it could be empty).
1319 So, what's the difference between using @code{MALLOC_CHECK_} and linking
1320 with @samp{-lmcheck}?  @code{MALLOC_CHECK_} is orthogonal with respect to
1321 @samp{-lmcheck}.  @samp{-lmcheck} has been added for backward
1322 compatibility.  Both @code{MALLOC_CHECK_} and @samp{-lmcheck} should
1323 uncover the same bugs - but using @code{MALLOC_CHECK_} you don't need to
1324 recompile your application.
1326 @node Hooks for Malloc
1327 @subsubsection Memory Allocation Hooks
1328 @cindex allocation hooks, for @code{malloc}
1330 @Theglibc{} lets you modify the behavior of @code{malloc},
1331 @code{realloc}, and @code{free} by specifying appropriate hook
1332 functions.  You can use these hooks to help you debug programs that use
1333 dynamic memory allocation, for example.
1335 The hook variables are declared in @file{malloc.h}.
1336 @pindex malloc.h
1338 @comment malloc.h
1339 @comment GNU
1340 @defvar __malloc_hook
1341 The value of this variable is a pointer to the function that
1342 @code{malloc} uses whenever it is called.  You should define this
1343 function to look like @code{malloc}; that is, like:
1345 @smallexample
1346 void *@var{function} (size_t @var{size}, const void *@var{caller})
1347 @end smallexample
1349 The value of @var{caller} is the return address found on the stack when
1350 the @code{malloc} function was called.  This value allows you to trace
1351 the memory consumption of the program.
1352 @end defvar
1354 @comment malloc.h
1355 @comment GNU
1356 @defvar __realloc_hook
1357 The value of this variable is a pointer to function that @code{realloc}
1358 uses whenever it is called.  You should define this function to look
1359 like @code{realloc}; that is, like:
1361 @smallexample
1362 void *@var{function} (void *@var{ptr}, size_t @var{size}, const void *@var{caller})
1363 @end smallexample
1365 The value of @var{caller} is the return address found on the stack when
1366 the @code{realloc} function was called.  This value allows you to trace the
1367 memory consumption of the program.
1368 @end defvar
1370 @comment malloc.h
1371 @comment GNU
1372 @defvar __free_hook
1373 The value of this variable is a pointer to function that @code{free}
1374 uses whenever it is called.  You should define this function to look
1375 like @code{free}; that is, like:
1377 @smallexample
1378 void @var{function} (void *@var{ptr}, const void *@var{caller})
1379 @end smallexample
1381 The value of @var{caller} is the return address found on the stack when
1382 the @code{free} function was called.  This value allows you to trace the
1383 memory consumption of the program.
1384 @end defvar
1386 @comment malloc.h
1387 @comment GNU
1388 @defvar __memalign_hook
1389 The value of this variable is a pointer to function that @code{aligned_alloc},
1390 @code{memalign}, @code{posix_memalign} and @code{valloc} use whenever they
1391 are called.  You should define this function to look like @code{aligned_alloc};
1392 that is, like:
1394 @smallexample
1395 void *@var{function} (size_t @var{alignment}, size_t @var{size}, const void *@var{caller})
1396 @end smallexample
1398 The value of @var{caller} is the return address found on the stack when
1399 the @code{aligned_alloc}, @code{memalign}, @code{posix_memalign} or
1400 @code{valloc} functions are called.  This value allows you to trace the
1401 memory consumption of the program.
1402 @end defvar
1404 You must make sure that the function you install as a hook for one of
1405 these functions does not call that function recursively without restoring
1406 the old value of the hook first!  Otherwise, your program will get stuck
1407 in an infinite recursion.  Before calling the function recursively, one
1408 should make sure to restore all the hooks to their previous value.  When
1409 coming back from the recursive call, all the hooks should be resaved
1410 since a hook might modify itself.
1412 An issue to look out for is the time at which the malloc hook functions
1413 can be safely installed.  If the hook functions call the malloc-related
1414 functions recursively, it is necessary that malloc has already properly
1415 initialized itself at the time when @code{__malloc_hook} etc. is
1416 assigned to.  On the other hand, if the hook functions provide a
1417 complete malloc implementation of their own, it is vital that the hooks
1418 are assigned to @emph{before} the very first @code{malloc} call has
1419 completed, because otherwise a chunk obtained from the ordinary,
1420 un-hooked malloc may later be handed to @code{__free_hook}, for example.
1422 Here is an example showing how to use @code{__malloc_hook} and
1423 @code{__free_hook} properly.  It installs a function that prints out
1424 information every time @code{malloc} or @code{free} is called.  We just
1425 assume here that @code{realloc} and @code{memalign} are not used in our
1426 program.
1428 @smallexample
1429 /* Prototypes for __malloc_hook, __free_hook */
1430 #include <malloc.h>
1432 /* Prototypes for our hooks.  */
1433 static void my_init_hook (void);
1434 static void *my_malloc_hook (size_t, const void *);
1435 static void my_free_hook (void*, const void *);
1437 static void
1438 my_init (void)
1440   old_malloc_hook = __malloc_hook;
1441   old_free_hook = __free_hook;
1442   __malloc_hook = my_malloc_hook;
1443   __free_hook = my_free_hook;
1446 static void *
1447 my_malloc_hook (size_t size, const void *caller)
1449   void *result;
1450   /* Restore all old hooks */
1451   __malloc_hook = old_malloc_hook;
1452   __free_hook = old_free_hook;
1453   /* Call recursively */
1454   result = malloc (size);
1455   /* Save underlying hooks */
1456   old_malloc_hook = __malloc_hook;
1457   old_free_hook = __free_hook;
1458   /* @r{@code{printf} might call @code{malloc}, so protect it too.} */
1459   printf ("malloc (%u) returns %p\n", (unsigned int) size, result);
1460   /* Restore our own hooks */
1461   __malloc_hook = my_malloc_hook;
1462   __free_hook = my_free_hook;
1463   return result;
1466 static void
1467 my_free_hook (void *ptr, const void *caller)
1469   /* Restore all old hooks */
1470   __malloc_hook = old_malloc_hook;
1471   __free_hook = old_free_hook;
1472   /* Call recursively */
1473   free (ptr);
1474   /* Save underlying hooks */
1475   old_malloc_hook = __malloc_hook;
1476   old_free_hook = __free_hook;
1477   /* @r{@code{printf} might call @code{free}, so protect it too.} */
1478   printf ("freed pointer %p\n", ptr);
1479   /* Restore our own hooks */
1480   __malloc_hook = my_malloc_hook;
1481   __free_hook = my_free_hook;
1484 main ()
1486   my_init ();
1487   @dots{}
1489 @end smallexample
1491 The @code{mcheck} function (@pxref{Heap Consistency Checking}) works by
1492 installing such hooks.
1494 @c __morecore, __after_morecore_hook are undocumented
1495 @c It's not clear whether to document them.
1497 @node Statistics of Malloc
1498 @subsubsection Statistics for Memory Allocation with @code{malloc}
1500 @cindex allocation statistics
1501 You can get information about dynamic memory allocation by calling the
1502 @code{mallinfo} function.  This function and its associated data type
1503 are declared in @file{malloc.h}; they are an extension of the standard
1504 SVID/XPG version.
1505 @pindex malloc.h
1507 @comment malloc.h
1508 @comment GNU
1509 @deftp {Data Type} {struct mallinfo}
1510 This structure type is used to return information about the dynamic
1511 memory allocator.  It contains the following members:
1513 @table @code
1514 @item int arena
1515 This is the total size of memory allocated with @code{sbrk} by
1516 @code{malloc}, in bytes.
1518 @item int ordblks
1519 This is the number of chunks not in use.  (The memory allocator
1520 internally gets chunks of memory from the operating system, and then
1521 carves them up to satisfy individual @code{malloc} requests;
1522 @pxref{The GNU Allocator}.)
1524 @item int smblks
1525 This field is unused.
1527 @item int hblks
1528 This is the total number of chunks allocated with @code{mmap}.
1530 @item int hblkhd
1531 This is the total size of memory allocated with @code{mmap}, in bytes.
1533 @item int usmblks
1534 This field is unused and always 0.
1536 @item int fsmblks
1537 This field is unused.
1539 @item int uordblks
1540 This is the total size of memory occupied by chunks handed out by
1541 @code{malloc}.
1543 @item int fordblks
1544 This is the total size of memory occupied by free (not in use) chunks.
1546 @item int keepcost
1547 This is the size of the top-most releasable chunk that normally
1548 borders the end of the heap (i.e., the high end of the virtual address
1549 space's data segment).
1551 @end table
1552 @end deftp
1554 @comment malloc.h
1555 @comment SVID
1556 @deftypefun {struct mallinfo} mallinfo (void)
1557 @safety{@prelim{}@mtunsafe{@mtuinit{} @mtasuconst{:mallopt}}@asunsafe{@asuinit{} @asulock{}}@acunsafe{@acuinit{} @aculock{}}}
1558 @c Accessing mp_.n_mmaps and mp_.max_mmapped_mem, modified with atomics
1559 @c but non-atomically elsewhere, may get us inconsistent results.  We
1560 @c mark the statistics as unsafe, rather than the fast-path functions
1561 @c that collect the possibly inconsistent data.
1563 @c __libc_mallinfo @mtuinit @mtasuconst:mallopt @asuinit @asulock @aculock
1564 @c  ptmalloc_init (once) dup @mtsenv @asulock @aculock @acsfd @acsmem
1565 @c  mutex_lock dup @asulock @aculock
1566 @c  int_mallinfo @mtasuconst:mallopt [mp_ access on main_arena]
1567 @c   malloc_consolidate dup ok
1568 @c   check_malloc_state dup ok/disabled
1569 @c   chunksize dup ok
1570 @c   fastbin dupo ok
1571 @c   bin_at dup ok
1572 @c   last dup ok
1573 @c  mutex_unlock @aculock
1575 This function returns information about the current dynamic memory usage
1576 in a structure of type @code{struct mallinfo}.
1577 @end deftypefun
1579 @node Summary of Malloc
1580 @subsubsection Summary of @code{malloc}-Related Functions
1582 Here is a summary of the functions that work with @code{malloc}:
1584 @table @code
1585 @item void *malloc (size_t @var{size})
1586 Allocate a block of @var{size} bytes.  @xref{Basic Allocation}.
1588 @item void free (void *@var{addr})
1589 Free a block previously allocated by @code{malloc}.  @xref{Freeing after
1590 Malloc}.
1592 @item void *realloc (void *@var{addr}, size_t @var{size})
1593 Make a block previously allocated by @code{malloc} larger or smaller,
1594 possibly by copying it to a new location.  @xref{Changing Block Size}.
1596 @item void *calloc (size_t @var{count}, size_t @var{eltsize})
1597 Allocate a block of @var{count} * @var{eltsize} bytes using
1598 @code{malloc}, and set its contents to zero.  @xref{Allocating Cleared
1599 Space}.
1601 @item void *valloc (size_t @var{size})
1602 Allocate a block of @var{size} bytes, starting on a page boundary.
1603 @xref{Aligned Memory Blocks}.
1605 @item void *aligned_alloc (size_t @var{size}, size_t @var{alignment})
1606 Allocate a block of @var{size} bytes, starting on an address that is a
1607 multiple of @var{alignment}.  @xref{Aligned Memory Blocks}.
1609 @item int posix_memalign (void **@var{memptr}, size_t @var{alignment}, size_t @var{size})
1610 Allocate a block of @var{size} bytes, starting on an address that is a
1611 multiple of @var{alignment}.  @xref{Aligned Memory Blocks}.
1613 @item void *memalign (size_t @var{size}, size_t @var{boundary})
1614 Allocate a block of @var{size} bytes, starting on an address that is a
1615 multiple of @var{boundary}.  @xref{Aligned Memory Blocks}.
1617 @item int mallopt (int @var{param}, int @var{value})
1618 Adjust a tunable parameter.  @xref{Malloc Tunable Parameters}.
1620 @item int mcheck (void (*@var{abortfn}) (void))
1621 Tell @code{malloc} to perform occasional consistency checks on
1622 dynamically allocated memory, and to call @var{abortfn} when an
1623 inconsistency is found.  @xref{Heap Consistency Checking}.
1625 @item void *(*__malloc_hook) (size_t @var{size}, const void *@var{caller})
1626 A pointer to a function that @code{malloc} uses whenever it is called.
1628 @item void *(*__realloc_hook) (void *@var{ptr}, size_t @var{size}, const void *@var{caller})
1629 A pointer to a function that @code{realloc} uses whenever it is called.
1631 @item void (*__free_hook) (void *@var{ptr}, const void *@var{caller})
1632 A pointer to a function that @code{free} uses whenever it is called.
1634 @item void (*__memalign_hook) (size_t @var{size}, size_t @var{alignment}, const void *@var{caller})
1635 A pointer to a function that @code{aligned_alloc}, @code{memalign},
1636 @code{posix_memalign} and @code{valloc} use whenever they are called.
1638 @item struct mallinfo mallinfo (void)
1639 Return information about the current dynamic memory usage.
1640 @xref{Statistics of Malloc}.
1641 @end table
1643 @node Allocation Debugging
1644 @subsection Allocation Debugging
1645 @cindex allocation debugging
1646 @cindex malloc debugger
1648 A complicated task when programming with languages which do not use
1649 garbage collected dynamic memory allocation is to find memory leaks.
1650 Long running programs must ensure that dynamically allocated objects are
1651 freed at the end of their lifetime.  If this does not happen the system
1652 runs out of memory, sooner or later.
1654 The @code{malloc} implementation in @theglibc{} provides some
1655 simple means to detect such leaks and obtain some information to find
1656 the location.  To do this the application must be started in a special
1657 mode which is enabled by an environment variable.  There are no speed
1658 penalties for the program if the debugging mode is not enabled.
1660 @menu
1661 * Tracing malloc::               How to install the tracing functionality.
1662 * Using the Memory Debugger::    Example programs excerpts.
1663 * Tips for the Memory Debugger:: Some more or less clever ideas.
1664 * Interpreting the traces::      What do all these lines mean?
1665 @end menu
1667 @node Tracing malloc
1668 @subsubsection How to install the tracing functionality
1670 @comment mcheck.h
1671 @comment GNU
1672 @deftypefun void mtrace (void)
1673 @safety{@prelim{}@mtunsafe{@mtsenv{} @mtasurace{:mtrace} @mtasuconst{:malloc_hooks} @mtuinit{}}@asunsafe{@asuinit{} @ascuheap{} @asucorrupt{} @asulock{}}@acunsafe{@acuinit{} @acucorrupt{} @aculock{} @acsfd{} @acsmem{}}}
1674 @c Like the mcheck hooks, these are not designed with thread safety in
1675 @c mind, because the hook pointers are temporarily modified without
1676 @c regard to other threads, signals or cancellation.
1678 @c mtrace @mtuinit @mtasurace:mtrace @mtsenv @asuinit @ascuheap @asucorrupt @acuinit @acucorrupt @aculock @acsfd @acsmem
1679 @c  __libc_secure_getenv dup @mtsenv
1680 @c  malloc dup @ascuheap @acsmem
1681 @c  fopen dup @ascuheap @asulock @aculock @acsmem @acsfd
1682 @c  fcntl dup ok
1683 @c  setvbuf dup @aculock
1684 @c  fprintf dup (on newly-created stream) @aculock
1685 @c  __cxa_atexit (once) dup @asulock @aculock @acsmem
1686 @c  free dup @ascuheap @acsmem
1687 When the @code{mtrace} function is called it looks for an environment
1688 variable named @code{MALLOC_TRACE}.  This variable is supposed to
1689 contain a valid file name.  The user must have write access.  If the
1690 file already exists it is truncated.  If the environment variable is not
1691 set or it does not name a valid file which can be opened for writing
1692 nothing is done.  The behavior of @code{malloc} etc. is not changed.
1693 For obvious reasons this also happens if the application is installed
1694 with the SUID or SGID bit set.
1696 If the named file is successfully opened, @code{mtrace} installs special
1697 handlers for the functions @code{malloc}, @code{realloc}, and
1698 @code{free} (@pxref{Hooks for Malloc}).  From then on, all uses of these
1699 functions are traced and protocolled into the file.  There is now of
1700 course a speed penalty for all calls to the traced functions so tracing
1701 should not be enabled during normal use.
1703 This function is a GNU extension and generally not available on other
1704 systems.  The prototype can be found in @file{mcheck.h}.
1705 @end deftypefun
1707 @comment mcheck.h
1708 @comment GNU
1709 @deftypefun void muntrace (void)
1710 @safety{@prelim{}@mtunsafe{@mtasurace{:mtrace} @mtasuconst{:malloc_hooks} @mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acucorrupt{} @acsmem{} @aculock{} @acsfd{}}}
1712 @c muntrace @mtasurace:mtrace @mtslocale @asucorrupt @ascuheap @acucorrupt @acsmem @aculock @acsfd
1713 @c  fprintf (fputs) dup @mtslocale @asucorrupt @ascuheap @acsmem @aculock @acucorrupt
1714 @c  fclose dup @ascuheap @asulock @aculock @acsmem @acsfd
1715 The @code{muntrace} function can be called after @code{mtrace} was used
1716 to enable tracing the @code{malloc} calls.  If no (successful) call of
1717 @code{mtrace} was made @code{muntrace} does nothing.
1719 Otherwise it deinstalls the handlers for @code{malloc}, @code{realloc},
1720 and @code{free} and then closes the protocol file.  No calls are
1721 protocolled anymore and the program runs again at full speed.
1723 This function is a GNU extension and generally not available on other
1724 systems.  The prototype can be found in @file{mcheck.h}.
1725 @end deftypefun
1727 @node Using the Memory Debugger
1728 @subsubsection Example program excerpts
1730 Even though the tracing functionality does not influence the runtime
1731 behavior of the program it is not a good idea to call @code{mtrace} in
1732 all programs.  Just imagine that you debug a program using @code{mtrace}
1733 and all other programs used in the debugging session also trace their
1734 @code{malloc} calls.  The output file would be the same for all programs
1735 and thus is unusable.  Therefore one should call @code{mtrace} only if
1736 compiled for debugging.  A program could therefore start like this:
1738 @example
1739 #include <mcheck.h>
1742 main (int argc, char *argv[])
1744 #ifdef DEBUGGING
1745   mtrace ();
1746 #endif
1747   @dots{}
1749 @end example
1751 This is all that is needed if you want to trace the calls during the
1752 whole runtime of the program.  Alternatively you can stop the tracing at
1753 any time with a call to @code{muntrace}.  It is even possible to restart
1754 the tracing again with a new call to @code{mtrace}.  But this can cause
1755 unreliable results since there may be calls of the functions which are
1756 not called.  Please note that not only the application uses the traced
1757 functions, also libraries (including the C library itself) use these
1758 functions.
1760 This last point is also why it is not a good idea to call @code{muntrace}
1761 before the program terminates.  The libraries are informed about the
1762 termination of the program only after the program returns from
1763 @code{main} or calls @code{exit} and so cannot free the memory they use
1764 before this time.
1766 So the best thing one can do is to call @code{mtrace} as the very first
1767 function in the program and never call @code{muntrace}.  So the program
1768 traces almost all uses of the @code{malloc} functions (except those
1769 calls which are executed by constructors of the program or used
1770 libraries).
1772 @node Tips for the Memory Debugger
1773 @subsubsection Some more or less clever ideas
1775 You know the situation.  The program is prepared for debugging and in
1776 all debugging sessions it runs well.  But once it is started without
1777 debugging the error shows up.  A typical example is a memory leak that
1778 becomes visible only when we turn off the debugging.  If you foresee
1779 such situations you can still win.  Simply use something equivalent to
1780 the following little program:
1782 @example
1783 #include <mcheck.h>
1784 #include <signal.h>
1786 static void
1787 enable (int sig)
1789   mtrace ();
1790   signal (SIGUSR1, enable);
1793 static void
1794 disable (int sig)
1796   muntrace ();
1797   signal (SIGUSR2, disable);
1801 main (int argc, char *argv[])
1803   @dots{}
1805   signal (SIGUSR1, enable);
1806   signal (SIGUSR2, disable);
1808   @dots{}
1810 @end example
1812 I.e., the user can start the memory debugger any time s/he wants if the
1813 program was started with @code{MALLOC_TRACE} set in the environment.
1814 The output will of course not show the allocations which happened before
1815 the first signal but if there is a memory leak this will show up
1816 nevertheless.
1818 @node Interpreting the traces
1819 @subsubsection Interpreting the traces
1821 If you take a look at the output it will look similar to this:
1823 @example
1824 = Start
1825 @ [0x8048209] - 0x8064cc8
1826 @ [0x8048209] - 0x8064ce0
1827 @ [0x8048209] - 0x8064cf8
1828 @ [0x80481eb] + 0x8064c48 0x14
1829 @ [0x80481eb] + 0x8064c60 0x14
1830 @ [0x80481eb] + 0x8064c78 0x14
1831 @ [0x80481eb] + 0x8064c90 0x14
1832 = End
1833 @end example
1835 What this all means is not really important since the trace file is not
1836 meant to be read by a human.  Therefore no attention is given to
1837 readability.  Instead there is a program which comes with @theglibc{}
1838 which interprets the traces and outputs a summary in an
1839 user-friendly way.  The program is called @code{mtrace} (it is in fact a
1840 Perl script) and it takes one or two arguments.  In any case the name of
1841 the file with the trace output must be specified.  If an optional
1842 argument precedes the name of the trace file this must be the name of
1843 the program which generated the trace.
1845 @example
1846 drepper$ mtrace tst-mtrace log
1847 No memory leaks.
1848 @end example
1850 In this case the program @code{tst-mtrace} was run and it produced a
1851 trace file @file{log}.  The message printed by @code{mtrace} shows there
1852 are no problems with the code, all allocated memory was freed
1853 afterwards.
1855 If we call @code{mtrace} on the example trace given above we would get a
1856 different outout:
1858 @example
1859 drepper$ mtrace errlog
1860 - 0x08064cc8 Free 2 was never alloc'd 0x8048209
1861 - 0x08064ce0 Free 3 was never alloc'd 0x8048209
1862 - 0x08064cf8 Free 4 was never alloc'd 0x8048209
1864 Memory not freed:
1865 -----------------
1866    Address     Size     Caller
1867 0x08064c48     0x14  at 0x80481eb
1868 0x08064c60     0x14  at 0x80481eb
1869 0x08064c78     0x14  at 0x80481eb
1870 0x08064c90     0x14  at 0x80481eb
1871 @end example
1873 We have called @code{mtrace} with only one argument and so the script
1874 has no chance to find out what is meant with the addresses given in the
1875 trace.  We can do better:
1877 @example
1878 drepper$ mtrace tst errlog
1879 - 0x08064cc8 Free 2 was never alloc'd /home/drepper/tst.c:39
1880 - 0x08064ce0 Free 3 was never alloc'd /home/drepper/tst.c:39
1881 - 0x08064cf8 Free 4 was never alloc'd /home/drepper/tst.c:39
1883 Memory not freed:
1884 -----------------
1885    Address     Size     Caller
1886 0x08064c48     0x14  at /home/drepper/tst.c:33
1887 0x08064c60     0x14  at /home/drepper/tst.c:33
1888 0x08064c78     0x14  at /home/drepper/tst.c:33
1889 0x08064c90     0x14  at /home/drepper/tst.c:33
1890 @end example
1892 Suddenly the output makes much more sense and the user can see
1893 immediately where the function calls causing the trouble can be found.
1895 Interpreting this output is not complicated.  There are at most two
1896 different situations being detected.  First, @code{free} was called for
1897 pointers which were never returned by one of the allocation functions.
1898 This is usually a very bad problem and what this looks like is shown in
1899 the first three lines of the output.  Situations like this are quite
1900 rare and if they appear they show up very drastically: the program
1901 normally crashes.
1903 The other situation which is much harder to detect are memory leaks.  As
1904 you can see in the output the @code{mtrace} function collects all this
1905 information and so can say that the program calls an allocation function
1906 from line 33 in the source file @file{/home/drepper/tst-mtrace.c} four
1907 times without freeing this memory before the program terminates.
1908 Whether this is a real problem remains to be investigated.
1910 @node Obstacks
1911 @subsection Obstacks
1912 @cindex obstacks
1914 An @dfn{obstack} is a pool of memory containing a stack of objects.  You
1915 can create any number of separate obstacks, and then allocate objects in
1916 specified obstacks.  Within each obstack, the last object allocated must
1917 always be the first one freed, but distinct obstacks are independent of
1918 each other.
1920 Aside from this one constraint of order of freeing, obstacks are totally
1921 general: an obstack can contain any number of objects of any size.  They
1922 are implemented with macros, so allocation is usually very fast as long as
1923 the objects are usually small.  And the only space overhead per object is
1924 the padding needed to start each object on a suitable boundary.
1926 @menu
1927 * Creating Obstacks::           How to declare an obstack in your program.
1928 * Preparing for Obstacks::      Preparations needed before you can
1929                                  use obstacks.
1930 * Allocation in an Obstack::    Allocating objects in an obstack.
1931 * Freeing Obstack Objects::     Freeing objects in an obstack.
1932 * Obstack Functions::           The obstack functions are both
1933                                  functions and macros.
1934 * Growing Objects::             Making an object bigger by stages.
1935 * Extra Fast Growing::          Extra-high-efficiency (though more
1936                                  complicated) growing objects.
1937 * Status of an Obstack::        Inquiries about the status of an obstack.
1938 * Obstacks Data Alignment::     Controlling alignment of objects in obstacks.
1939 * Obstack Chunks::              How obstacks obtain and release chunks;
1940                                  efficiency considerations.
1941 * Summary of Obstacks::
1942 @end menu
1944 @node Creating Obstacks
1945 @subsubsection Creating Obstacks
1947 The utilities for manipulating obstacks are declared in the header
1948 file @file{obstack.h}.
1949 @pindex obstack.h
1951 @comment obstack.h
1952 @comment GNU
1953 @deftp {Data Type} {struct obstack}
1954 An obstack is represented by a data structure of type @code{struct
1955 obstack}.  This structure has a small fixed size; it records the status
1956 of the obstack and how to find the space in which objects are allocated.
1957 It does not contain any of the objects themselves.  You should not try
1958 to access the contents of the structure directly; use only the functions
1959 described in this chapter.
1960 @end deftp
1962 You can declare variables of type @code{struct obstack} and use them as
1963 obstacks, or you can allocate obstacks dynamically like any other kind
1964 of object.  Dynamic allocation of obstacks allows your program to have a
1965 variable number of different stacks.  (You can even allocate an
1966 obstack structure in another obstack, but this is rarely useful.)
1968 All the functions that work with obstacks require you to specify which
1969 obstack to use.  You do this with a pointer of type @code{struct obstack
1970 *}.  In the following, we often say ``an obstack'' when strictly
1971 speaking the object at hand is such a pointer.
1973 The objects in the obstack are packed into large blocks called
1974 @dfn{chunks}.  The @code{struct obstack} structure points to a chain of
1975 the chunks currently in use.
1977 The obstack library obtains a new chunk whenever you allocate an object
1978 that won't fit in the previous chunk.  Since the obstack library manages
1979 chunks automatically, you don't need to pay much attention to them, but
1980 you do need to supply a function which the obstack library should use to
1981 get a chunk.  Usually you supply a function which uses @code{malloc}
1982 directly or indirectly.  You must also supply a function to free a chunk.
1983 These matters are described in the following section.
1985 @node Preparing for Obstacks
1986 @subsubsection Preparing for Using Obstacks
1988 Each source file in which you plan to use the obstack functions
1989 must include the header file @file{obstack.h}, like this:
1991 @smallexample
1992 #include <obstack.h>
1993 @end smallexample
1995 @findex obstack_chunk_alloc
1996 @findex obstack_chunk_free
1997 Also, if the source file uses the macro @code{obstack_init}, it must
1998 declare or define two functions or macros that will be called by the
1999 obstack library.  One, @code{obstack_chunk_alloc}, is used to allocate
2000 the chunks of memory into which objects are packed.  The other,
2001 @code{obstack_chunk_free}, is used to return chunks when the objects in
2002 them are freed.  These macros should appear before any use of obstacks
2003 in the source file.
2005 Usually these are defined to use @code{malloc} via the intermediary
2006 @code{xmalloc} (@pxref{Unconstrained Allocation}).  This is done with
2007 the following pair of macro definitions:
2009 @smallexample
2010 #define obstack_chunk_alloc xmalloc
2011 #define obstack_chunk_free free
2012 @end smallexample
2014 @noindent
2015 Though the memory you get using obstacks really comes from @code{malloc},
2016 using obstacks is faster because @code{malloc} is called less often, for
2017 larger blocks of memory.  @xref{Obstack Chunks}, for full details.
2019 At run time, before the program can use a @code{struct obstack} object
2020 as an obstack, it must initialize the obstack by calling
2021 @code{obstack_init}.
2023 @comment obstack.h
2024 @comment GNU
2025 @deftypefun int obstack_init (struct obstack *@var{obstack-ptr})
2026 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{@acsmem{}}}
2027 @c obstack_init @mtsrace:obstack-ptr @acsmem
2028 @c  _obstack_begin @acsmem
2029 @c    chunkfun = obstack_chunk_alloc (suggested malloc)
2030 @c    freefun = obstack_chunk_free (suggested free)
2031 @c   *chunkfun @acsmem
2032 @c    obstack_chunk_alloc user-supplied
2033 @c   *obstack_alloc_failed_handler user-supplied
2034 @c    -> print_and_abort (default)
2036 @c print_and_abort
2037 @c  _ dup @ascuintl
2038 @c  fxprintf dup @asucorrupt @aculock @acucorrupt
2039 @c  exit @acucorrupt?
2040 Initialize obstack @var{obstack-ptr} for allocation of objects.  This
2041 function calls the obstack's @code{obstack_chunk_alloc} function.  If
2042 allocation of memory fails, the function pointed to by
2043 @code{obstack_alloc_failed_handler} is called.  The @code{obstack_init}
2044 function always returns 1 (Compatibility notice: Former versions of
2045 obstack returned 0 if allocation failed).
2046 @end deftypefun
2048 Here are two examples of how to allocate the space for an obstack and
2049 initialize it.  First, an obstack that is a static variable:
2051 @smallexample
2052 static struct obstack myobstack;
2053 @dots{}
2054 obstack_init (&myobstack);
2055 @end smallexample
2057 @noindent
2058 Second, an obstack that is itself dynamically allocated:
2060 @smallexample
2061 struct obstack *myobstack_ptr
2062   = (struct obstack *) xmalloc (sizeof (struct obstack));
2064 obstack_init (myobstack_ptr);
2065 @end smallexample
2067 @comment obstack.h
2068 @comment GNU
2069 @defvar obstack_alloc_failed_handler
2070 The value of this variable is a pointer to a function that
2071 @code{obstack} uses when @code{obstack_chunk_alloc} fails to allocate
2072 memory.  The default action is to print a message and abort.
2073 You should supply a function that either calls @code{exit}
2074 (@pxref{Program Termination}) or @code{longjmp} (@pxref{Non-Local
2075 Exits}) and doesn't return.
2077 @smallexample
2078 void my_obstack_alloc_failed (void)
2079 @dots{}
2080 obstack_alloc_failed_handler = &my_obstack_alloc_failed;
2081 @end smallexample
2083 @end defvar
2085 @node Allocation in an Obstack
2086 @subsubsection Allocation in an Obstack
2087 @cindex allocation (obstacks)
2089 The most direct way to allocate an object in an obstack is with
2090 @code{obstack_alloc}, which is invoked almost like @code{malloc}.
2092 @comment obstack.h
2093 @comment GNU
2094 @deftypefun {void *} obstack_alloc (struct obstack *@var{obstack-ptr}, int @var{size})
2095 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2096 @c obstack_alloc @mtsrace:obstack-ptr @acucorrupt @acsmem
2097 @c  obstack_blank dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2098 @c  obstack_finish dup @mtsrace:obstack-ptr @acucorrupt
2099 This allocates an uninitialized block of @var{size} bytes in an obstack
2100 and returns its address.  Here @var{obstack-ptr} specifies which obstack
2101 to allocate the block in; it is the address of the @code{struct obstack}
2102 object which represents the obstack.  Each obstack function or macro
2103 requires you to specify an @var{obstack-ptr} as the first argument.
2105 This function calls the obstack's @code{obstack_chunk_alloc} function if
2106 it needs to allocate a new chunk of memory; it calls
2107 @code{obstack_alloc_failed_handler} if allocation of memory by
2108 @code{obstack_chunk_alloc} failed.
2109 @end deftypefun
2111 For example, here is a function that allocates a copy of a string @var{str}
2112 in a specific obstack, which is in the variable @code{string_obstack}:
2114 @smallexample
2115 struct obstack string_obstack;
2117 char *
2118 copystring (char *string)
2120   size_t len = strlen (string) + 1;
2121   char *s = (char *) obstack_alloc (&string_obstack, len);
2122   memcpy (s, string, len);
2123   return s;
2125 @end smallexample
2127 To allocate a block with specified contents, use the function
2128 @code{obstack_copy}, declared like this:
2130 @comment obstack.h
2131 @comment GNU
2132 @deftypefun {void *} obstack_copy (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2133 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2134 @c obstack_copy @mtsrace:obstack-ptr @acucorrupt @acsmem
2135 @c  obstack_grow dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2136 @c  obstack_finish dup @mtsrace:obstack-ptr @acucorrupt
2137 This allocates a block and initializes it by copying @var{size}
2138 bytes of data starting at @var{address}.  It calls
2139 @code{obstack_alloc_failed_handler} if allocation of memory by
2140 @code{obstack_chunk_alloc} failed.
2141 @end deftypefun
2143 @comment obstack.h
2144 @comment GNU
2145 @deftypefun {void *} obstack_copy0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2146 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2147 @c obstack_copy0 @mtsrace:obstack-ptr @acucorrupt @acsmem
2148 @c  obstack_grow0 dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2149 @c  obstack_finish dup @mtsrace:obstack-ptr @acucorrupt
2150 Like @code{obstack_copy}, but appends an extra byte containing a null
2151 character.  This extra byte is not counted in the argument @var{size}.
2152 @end deftypefun
2154 The @code{obstack_copy0} function is convenient for copying a sequence
2155 of characters into an obstack as a null-terminated string.  Here is an
2156 example of its use:
2158 @smallexample
2159 char *
2160 obstack_savestring (char *addr, int size)
2162   return obstack_copy0 (&myobstack, addr, size);
2164 @end smallexample
2166 @noindent
2167 Contrast this with the previous example of @code{savestring} using
2168 @code{malloc} (@pxref{Basic Allocation}).
2170 @node Freeing Obstack Objects
2171 @subsubsection Freeing Objects in an Obstack
2172 @cindex freeing (obstacks)
2174 To free an object allocated in an obstack, use the function
2175 @code{obstack_free}.  Since the obstack is a stack of objects, freeing
2176 one object automatically frees all other objects allocated more recently
2177 in the same obstack.
2179 @comment obstack.h
2180 @comment GNU
2181 @deftypefun void obstack_free (struct obstack *@var{obstack-ptr}, void *@var{object})
2182 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{}}}
2183 @c obstack_free @mtsrace:obstack-ptr @acucorrupt
2184 @c  (obstack_free) @mtsrace:obstack-ptr @acucorrupt
2185 @c   *freefun dup user-supplied
2186 If @var{object} is a null pointer, everything allocated in the obstack
2187 is freed.  Otherwise, @var{object} must be the address of an object
2188 allocated in the obstack.  Then @var{object} is freed, along with
2189 everything allocated in @var{obstack-ptr} since @var{object}.
2190 @end deftypefun
2192 Note that if @var{object} is a null pointer, the result is an
2193 uninitialized obstack.  To free all memory in an obstack but leave it
2194 valid for further allocation, call @code{obstack_free} with the address
2195 of the first object allocated on the obstack:
2197 @smallexample
2198 obstack_free (obstack_ptr, first_object_allocated_ptr);
2199 @end smallexample
2201 Recall that the objects in an obstack are grouped into chunks.  When all
2202 the objects in a chunk become free, the obstack library automatically
2203 frees the chunk (@pxref{Preparing for Obstacks}).  Then other
2204 obstacks, or non-obstack allocation, can reuse the space of the chunk.
2206 @node Obstack Functions
2207 @subsubsection Obstack Functions and Macros
2208 @cindex macros
2210 The interfaces for using obstacks may be defined either as functions or
2211 as macros, depending on the compiler.  The obstack facility works with
2212 all C compilers, including both @w{ISO C} and traditional C, but there are
2213 precautions you must take if you plan to use compilers other than GNU C.
2215 If you are using an old-fashioned @w{non-ISO C} compiler, all the obstack
2216 ``functions'' are actually defined only as macros.  You can call these
2217 macros like functions, but you cannot use them in any other way (for
2218 example, you cannot take their address).
2220 Calling the macros requires a special precaution: namely, the first
2221 operand (the obstack pointer) may not contain any side effects, because
2222 it may be computed more than once.  For example, if you write this:
2224 @smallexample
2225 obstack_alloc (get_obstack (), 4);
2226 @end smallexample
2228 @noindent
2229 you will find that @code{get_obstack} may be called several times.
2230 If you use @code{*obstack_list_ptr++} as the obstack pointer argument,
2231 you will get very strange results since the incrementation may occur
2232 several times.
2234 In @w{ISO C}, each function has both a macro definition and a function
2235 definition.  The function definition is used if you take the address of the
2236 function without calling it.  An ordinary call uses the macro definition by
2237 default, but you can request the function definition instead by writing the
2238 function name in parentheses, as shown here:
2240 @smallexample
2241 char *x;
2242 void *(*funcp) ();
2243 /* @r{Use the macro}.  */
2244 x = (char *) obstack_alloc (obptr, size);
2245 /* @r{Call the function}.  */
2246 x = (char *) (obstack_alloc) (obptr, size);
2247 /* @r{Take the address of the function}.  */
2248 funcp = obstack_alloc;
2249 @end smallexample
2251 @noindent
2252 This is the same situation that exists in @w{ISO C} for the standard library
2253 functions.  @xref{Macro Definitions}.
2255 @strong{Warning:} When you do use the macros, you must observe the
2256 precaution of avoiding side effects in the first operand, even in @w{ISO C}.
2258 If you use the GNU C compiler, this precaution is not necessary, because
2259 various language extensions in GNU C permit defining the macros so as to
2260 compute each argument only once.
2262 @node Growing Objects
2263 @subsubsection Growing Objects
2264 @cindex growing objects (in obstacks)
2265 @cindex changing the size of a block (obstacks)
2267 Because memory in obstack chunks is used sequentially, it is possible to
2268 build up an object step by step, adding one or more bytes at a time to the
2269 end of the object.  With this technique, you do not need to know how much
2270 data you will put in the object until you come to the end of it.  We call
2271 this the technique of @dfn{growing objects}.  The special functions
2272 for adding data to the growing object are described in this section.
2274 You don't need to do anything special when you start to grow an object.
2275 Using one of the functions to add data to the object automatically
2276 starts it.  However, it is necessary to say explicitly when the object is
2277 finished.  This is done with the function @code{obstack_finish}.
2279 The actual address of the object thus built up is not known until the
2280 object is finished.  Until then, it always remains possible that you will
2281 add so much data that the object must be copied into a new chunk.
2283 While the obstack is in use for a growing object, you cannot use it for
2284 ordinary allocation of another object.  If you try to do so, the space
2285 already added to the growing object will become part of the other object.
2287 @comment obstack.h
2288 @comment GNU
2289 @deftypefun void obstack_blank (struct obstack *@var{obstack-ptr}, int @var{size})
2290 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2291 @c obstack_blank @mtsrace:obstack-ptr @acucorrupt @acsmem
2292 @c  _obstack_newchunk @mtsrace:obstack-ptr @acucorrupt @acsmem
2293 @c   *chunkfun dup @acsmem
2294 @c   *obstack_alloc_failed_handler dup user-supplied
2295 @c   *freefun
2296 @c  obstack_blank_fast dup @mtsrace:obstack-ptr
2297 The most basic function for adding to a growing object is
2298 @code{obstack_blank}, which adds space without initializing it.
2299 @end deftypefun
2301 @comment obstack.h
2302 @comment GNU
2303 @deftypefun void obstack_grow (struct obstack *@var{obstack-ptr}, void *@var{data}, int @var{size})
2304 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2305 @c obstack_grow @mtsrace:obstack-ptr @acucorrupt @acsmem
2306 @c  _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2307 @c  memcpy ok
2308 To add a block of initialized space, use @code{obstack_grow}, which is
2309 the growing-object analogue of @code{obstack_copy}.  It adds @var{size}
2310 bytes of data to the growing object, copying the contents from
2311 @var{data}.
2312 @end deftypefun
2314 @comment obstack.h
2315 @comment GNU
2316 @deftypefun void obstack_grow0 (struct obstack *@var{obstack-ptr}, void *@var{data}, int @var{size})
2317 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2318 @c obstack_grow0 @mtsrace:obstack-ptr @acucorrupt @acsmem
2319 @c   (no sequence point between storing NUL and incrementing next_free)
2320 @c   (multiple changes to next_free => @acucorrupt)
2321 @c  _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2322 @c  memcpy ok
2323 This is the growing-object analogue of @code{obstack_copy0}.  It adds
2324 @var{size} bytes copied from @var{data}, followed by an additional null
2325 character.
2326 @end deftypefun
2328 @comment obstack.h
2329 @comment GNU
2330 @deftypefun void obstack_1grow (struct obstack *@var{obstack-ptr}, char @var{c})
2331 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2332 @c obstack_1grow @mtsrace:obstack-ptr @acucorrupt @acsmem
2333 @c  _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2334 @c  obstack_1grow_fast dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2335 To add one character at a time, use the function @code{obstack_1grow}.
2336 It adds a single byte containing @var{c} to the growing object.
2337 @end deftypefun
2339 @comment obstack.h
2340 @comment GNU
2341 @deftypefun void obstack_ptr_grow (struct obstack *@var{obstack-ptr}, void *@var{data})
2342 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2343 @c obstack_ptr_grow @mtsrace:obstack-ptr @acucorrupt @acsmem
2344 @c  _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2345 @c  obstack_ptr_grow_fast dup @mtsrace:obstack-ptr
2346 Adding the value of a pointer one can use the function
2347 @code{obstack_ptr_grow}.  It adds @code{sizeof (void *)} bytes
2348 containing the value of @var{data}.
2349 @end deftypefun
2351 @comment obstack.h
2352 @comment GNU
2353 @deftypefun void obstack_int_grow (struct obstack *@var{obstack-ptr}, int @var{data})
2354 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2355 @c obstack_int_grow @mtsrace:obstack-ptr @acucorrupt @acsmem
2356 @c  _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2357 @c  obstack_int_grow_fast dup @mtsrace:obstack-ptr
2358 A single value of type @code{int} can be added by using the
2359 @code{obstack_int_grow} function.  It adds @code{sizeof (int)} bytes to
2360 the growing object and initializes them with the value of @var{data}.
2361 @end deftypefun
2363 @comment obstack.h
2364 @comment GNU
2365 @deftypefun {void *} obstack_finish (struct obstack *@var{obstack-ptr})
2366 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{}}}
2367 @c obstack_finish @mtsrace:obstack-ptr @acucorrupt
2368 When you are finished growing the object, use the function
2369 @code{obstack_finish} to close it off and return its final address.
2371 Once you have finished the object, the obstack is available for ordinary
2372 allocation or for growing another object.
2374 This function can return a null pointer under the same conditions as
2375 @code{obstack_alloc} (@pxref{Allocation in an Obstack}).
2376 @end deftypefun
2378 When you build an object by growing it, you will probably need to know
2379 afterward how long it became.  You need not keep track of this as you grow
2380 the object, because you can find out the length from the obstack just
2381 before finishing the object with the function @code{obstack_object_size},
2382 declared as follows:
2384 @comment obstack.h
2385 @comment GNU
2386 @deftypefun int obstack_object_size (struct obstack *@var{obstack-ptr})
2387 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
2388 This function returns the current size of the growing object, in bytes.
2389 Remember to call this function @emph{before} finishing the object.
2390 After it is finished, @code{obstack_object_size} will return zero.
2391 @end deftypefun
2393 If you have started growing an object and wish to cancel it, you should
2394 finish it and then free it, like this:
2396 @smallexample
2397 obstack_free (obstack_ptr, obstack_finish (obstack_ptr));
2398 @end smallexample
2400 @noindent
2401 This has no effect if no object was growing.
2403 @cindex shrinking objects
2404 You can use @code{obstack_blank} with a negative size argument to make
2405 the current object smaller.  Just don't try to shrink it beyond zero
2406 length---there's no telling what will happen if you do that.
2408 @node Extra Fast Growing
2409 @subsubsection Extra Fast Growing Objects
2410 @cindex efficiency and obstacks
2412 The usual functions for growing objects incur overhead for checking
2413 whether there is room for the new growth in the current chunk.  If you
2414 are frequently constructing objects in small steps of growth, this
2415 overhead can be significant.
2417 You can reduce the overhead by using special ``fast growth''
2418 functions that grow the object without checking.  In order to have a
2419 robust program, you must do the checking yourself.  If you do this checking
2420 in the simplest way each time you are about to add data to the object, you
2421 have not saved anything, because that is what the ordinary growth
2422 functions do.  But if you can arrange to check less often, or check
2423 more efficiently, then you make the program faster.
2425 The function @code{obstack_room} returns the amount of room available
2426 in the current chunk.  It is declared as follows:
2428 @comment obstack.h
2429 @comment GNU
2430 @deftypefun int obstack_room (struct obstack *@var{obstack-ptr})
2431 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
2432 This returns the number of bytes that can be added safely to the current
2433 growing object (or to an object about to be started) in obstack
2434 @var{obstack-ptr} using the fast growth functions.
2435 @end deftypefun
2437 While you know there is room, you can use these fast growth functions
2438 for adding data to a growing object:
2440 @comment obstack.h
2441 @comment GNU
2442 @deftypefun void obstack_1grow_fast (struct obstack *@var{obstack-ptr}, char @var{c})
2443 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2444 @c obstack_1grow_fast @mtsrace:obstack-ptr @acucorrupt @acsmem
2445 @c   (no sequence point between copying c and incrementing next_free)
2446 The function @code{obstack_1grow_fast} adds one byte containing the
2447 character @var{c} to the growing object in obstack @var{obstack-ptr}.
2448 @end deftypefun
2450 @comment obstack.h
2451 @comment GNU
2452 @deftypefun void obstack_ptr_grow_fast (struct obstack *@var{obstack-ptr}, void *@var{data})
2453 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
2454 @c obstack_ptr_grow_fast @mtsrace:obstack-ptr
2455 The function @code{obstack_ptr_grow_fast} adds @code{sizeof (void *)}
2456 bytes containing the value of @var{data} to the growing object in
2457 obstack @var{obstack-ptr}.
2458 @end deftypefun
2460 @comment obstack.h
2461 @comment GNU
2462 @deftypefun void obstack_int_grow_fast (struct obstack *@var{obstack-ptr}, int @var{data})
2463 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
2464 @c obstack_int_grow_fast @mtsrace:obstack-ptr
2465 The function @code{obstack_int_grow_fast} adds @code{sizeof (int)} bytes
2466 containing the value of @var{data} to the growing object in obstack
2467 @var{obstack-ptr}.
2468 @end deftypefun
2470 @comment obstack.h
2471 @comment GNU
2472 @deftypefun void obstack_blank_fast (struct obstack *@var{obstack-ptr}, int @var{size})
2473 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
2474 @c obstack_blank_fast @mtsrace:obstack-ptr
2475 The function @code{obstack_blank_fast} adds @var{size} bytes to the
2476 growing object in obstack @var{obstack-ptr} without initializing them.
2477 @end deftypefun
2479 When you check for space using @code{obstack_room} and there is not
2480 enough room for what you want to add, the fast growth functions
2481 are not safe.  In this case, simply use the corresponding ordinary
2482 growth function instead.  Very soon this will copy the object to a
2483 new chunk; then there will be lots of room available again.
2485 So, each time you use an ordinary growth function, check afterward for
2486 sufficient space using @code{obstack_room}.  Once the object is copied
2487 to a new chunk, there will be plenty of space again, so the program will
2488 start using the fast growth functions again.
2490 Here is an example:
2492 @smallexample
2493 @group
2494 void
2495 add_string (struct obstack *obstack, const char *ptr, int len)
2497   while (len > 0)
2498     @{
2499       int room = obstack_room (obstack);
2500       if (room == 0)
2501         @{
2502           /* @r{Not enough room.  Add one character slowly,}
2503              @r{which may copy to a new chunk and make room.}  */
2504           obstack_1grow (obstack, *ptr++);
2505           len--;
2506         @}
2507       else
2508         @{
2509           if (room > len)
2510             room = len;
2511           /* @r{Add fast as much as we have room for.} */
2512           len -= room;
2513           while (room-- > 0)
2514             obstack_1grow_fast (obstack, *ptr++);
2515         @}
2516     @}
2518 @end group
2519 @end smallexample
2521 @node Status of an Obstack
2522 @subsubsection Status of an Obstack
2523 @cindex obstack status
2524 @cindex status of obstack
2526 Here are functions that provide information on the current status of
2527 allocation in an obstack.  You can use them to learn about an object while
2528 still growing it.
2530 @comment obstack.h
2531 @comment GNU
2532 @deftypefun {void *} obstack_base (struct obstack *@var{obstack-ptr})
2533 @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acsafe{}}
2534 This function returns the tentative address of the beginning of the
2535 currently growing object in @var{obstack-ptr}.  If you finish the object
2536 immediately, it will have that address.  If you make it larger first, it
2537 may outgrow the current chunk---then its address will change!
2539 If no object is growing, this value says where the next object you
2540 allocate will start (once again assuming it fits in the current
2541 chunk).
2542 @end deftypefun
2544 @comment obstack.h
2545 @comment GNU
2546 @deftypefun {void *} obstack_next_free (struct obstack *@var{obstack-ptr})
2547 @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acsafe{}}
2548 This function returns the address of the first free byte in the current
2549 chunk of obstack @var{obstack-ptr}.  This is the end of the currently
2550 growing object.  If no object is growing, @code{obstack_next_free}
2551 returns the same value as @code{obstack_base}.
2552 @end deftypefun
2554 @comment obstack.h
2555 @comment GNU
2556 @deftypefun int obstack_object_size (struct obstack *@var{obstack-ptr})
2557 @c dup
2558 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
2559 This function returns the size in bytes of the currently growing object.
2560 This is equivalent to
2562 @smallexample
2563 obstack_next_free (@var{obstack-ptr}) - obstack_base (@var{obstack-ptr})
2564 @end smallexample
2565 @end deftypefun
2567 @node Obstacks Data Alignment
2568 @subsubsection Alignment of Data in Obstacks
2569 @cindex alignment (in obstacks)
2571 Each obstack has an @dfn{alignment boundary}; each object allocated in
2572 the obstack automatically starts on an address that is a multiple of the
2573 specified boundary.  By default, this boundary is aligned so that
2574 the object can hold any type of data.
2576 To access an obstack's alignment boundary, use the macro
2577 @code{obstack_alignment_mask}, whose function prototype looks like
2578 this:
2580 @comment obstack.h
2581 @comment GNU
2582 @deftypefn Macro int obstack_alignment_mask (struct obstack *@var{obstack-ptr})
2583 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2584 The value is a bit mask; a bit that is 1 indicates that the corresponding
2585 bit in the address of an object should be 0.  The mask value should be one
2586 less than a power of 2; the effect is that all object addresses are
2587 multiples of that power of 2.  The default value of the mask is a value
2588 that allows aligned objects to hold any type of data: for example, if
2589 its value is 3, any type of data can be stored at locations whose
2590 addresses are multiples of 4.  A mask value of 0 means an object can start
2591 on any multiple of 1 (that is, no alignment is required).
2593 The expansion of the macro @code{obstack_alignment_mask} is an lvalue,
2594 so you can alter the mask by assignment.  For example, this statement:
2596 @smallexample
2597 obstack_alignment_mask (obstack_ptr) = 0;
2598 @end smallexample
2600 @noindent
2601 has the effect of turning off alignment processing in the specified obstack.
2602 @end deftypefn
2604 Note that a change in alignment mask does not take effect until
2605 @emph{after} the next time an object is allocated or finished in the
2606 obstack.  If you are not growing an object, you can make the new
2607 alignment mask take effect immediately by calling @code{obstack_finish}.
2608 This will finish a zero-length object and then do proper alignment for
2609 the next object.
2611 @node Obstack Chunks
2612 @subsubsection Obstack Chunks
2613 @cindex efficiency of chunks
2614 @cindex chunks
2616 Obstacks work by allocating space for themselves in large chunks, and
2617 then parceling out space in the chunks to satisfy your requests.  Chunks
2618 are normally 4096 bytes long unless you specify a different chunk size.
2619 The chunk size includes 8 bytes of overhead that are not actually used
2620 for storing objects.  Regardless of the specified size, longer chunks
2621 will be allocated when necessary for long objects.
2623 The obstack library allocates chunks by calling the function
2624 @code{obstack_chunk_alloc}, which you must define.  When a chunk is no
2625 longer needed because you have freed all the objects in it, the obstack
2626 library frees the chunk by calling @code{obstack_chunk_free}, which you
2627 must also define.
2629 These two must be defined (as macros) or declared (as functions) in each
2630 source file that uses @code{obstack_init} (@pxref{Creating Obstacks}).
2631 Most often they are defined as macros like this:
2633 @smallexample
2634 #define obstack_chunk_alloc malloc
2635 #define obstack_chunk_free free
2636 @end smallexample
2638 Note that these are simple macros (no arguments).  Macro definitions with
2639 arguments will not work!  It is necessary that @code{obstack_chunk_alloc}
2640 or @code{obstack_chunk_free}, alone, expand into a function name if it is
2641 not itself a function name.
2643 If you allocate chunks with @code{malloc}, the chunk size should be a
2644 power of 2.  The default chunk size, 4096, was chosen because it is long
2645 enough to satisfy many typical requests on the obstack yet short enough
2646 not to waste too much memory in the portion of the last chunk not yet used.
2648 @comment obstack.h
2649 @comment GNU
2650 @deftypefn Macro int obstack_chunk_size (struct obstack *@var{obstack-ptr})
2651 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2652 This returns the chunk size of the given obstack.
2653 @end deftypefn
2655 Since this macro expands to an lvalue, you can specify a new chunk size by
2656 assigning it a new value.  Doing so does not affect the chunks already
2657 allocated, but will change the size of chunks allocated for that particular
2658 obstack in the future.  It is unlikely to be useful to make the chunk size
2659 smaller, but making it larger might improve efficiency if you are
2660 allocating many objects whose size is comparable to the chunk size.  Here
2661 is how to do so cleanly:
2663 @smallexample
2664 if (obstack_chunk_size (obstack_ptr) < @var{new-chunk-size})
2665   obstack_chunk_size (obstack_ptr) = @var{new-chunk-size};
2666 @end smallexample
2668 @node Summary of Obstacks
2669 @subsubsection Summary of Obstack Functions
2671 Here is a summary of all the functions associated with obstacks.  Each
2672 takes the address of an obstack (@code{struct obstack *}) as its first
2673 argument.
2675 @table @code
2676 @item void obstack_init (struct obstack *@var{obstack-ptr})
2677 Initialize use of an obstack.  @xref{Creating Obstacks}.
2679 @item void *obstack_alloc (struct obstack *@var{obstack-ptr}, int @var{size})
2680 Allocate an object of @var{size} uninitialized bytes.
2681 @xref{Allocation in an Obstack}.
2683 @item void *obstack_copy (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2684 Allocate an object of @var{size} bytes, with contents copied from
2685 @var{address}.  @xref{Allocation in an Obstack}.
2687 @item void *obstack_copy0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2688 Allocate an object of @var{size}+1 bytes, with @var{size} of them copied
2689 from @var{address}, followed by a null character at the end.
2690 @xref{Allocation in an Obstack}.
2692 @item void obstack_free (struct obstack *@var{obstack-ptr}, void *@var{object})
2693 Free @var{object} (and everything allocated in the specified obstack
2694 more recently than @var{object}).  @xref{Freeing Obstack Objects}.
2696 @item void obstack_blank (struct obstack *@var{obstack-ptr}, int @var{size})
2697 Add @var{size} uninitialized bytes to a growing object.
2698 @xref{Growing Objects}.
2700 @item void obstack_grow (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2701 Add @var{size} bytes, copied from @var{address}, to a growing object.
2702 @xref{Growing Objects}.
2704 @item void obstack_grow0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2705 Add @var{size} bytes, copied from @var{address}, to a growing object,
2706 and then add another byte containing a null character.  @xref{Growing
2707 Objects}.
2709 @item void obstack_1grow (struct obstack *@var{obstack-ptr}, char @var{data-char})
2710 Add one byte containing @var{data-char} to a growing object.
2711 @xref{Growing Objects}.
2713 @item void *obstack_finish (struct obstack *@var{obstack-ptr})
2714 Finalize the object that is growing and return its permanent address.
2715 @xref{Growing Objects}.
2717 @item int obstack_object_size (struct obstack *@var{obstack-ptr})
2718 Get the current size of the currently growing object.  @xref{Growing
2719 Objects}.
2721 @item void obstack_blank_fast (struct obstack *@var{obstack-ptr}, int @var{size})
2722 Add @var{size} uninitialized bytes to a growing object without checking
2723 that there is enough room.  @xref{Extra Fast Growing}.
2725 @item void obstack_1grow_fast (struct obstack *@var{obstack-ptr}, char @var{data-char})
2726 Add one byte containing @var{data-char} to a growing object without
2727 checking that there is enough room.  @xref{Extra Fast Growing}.
2729 @item int obstack_room (struct obstack *@var{obstack-ptr})
2730 Get the amount of room now available for growing the current object.
2731 @xref{Extra Fast Growing}.
2733 @item int obstack_alignment_mask (struct obstack *@var{obstack-ptr})
2734 The mask used for aligning the beginning of an object.  This is an
2735 lvalue.  @xref{Obstacks Data Alignment}.
2737 @item int obstack_chunk_size (struct obstack *@var{obstack-ptr})
2738 The size for allocating chunks.  This is an lvalue.  @xref{Obstack Chunks}.
2740 @item void *obstack_base (struct obstack *@var{obstack-ptr})
2741 Tentative starting address of the currently growing object.
2742 @xref{Status of an Obstack}.
2744 @item void *obstack_next_free (struct obstack *@var{obstack-ptr})
2745 Address just after the end of the currently growing object.
2746 @xref{Status of an Obstack}.
2747 @end table
2749 @node Variable Size Automatic
2750 @subsection Automatic Storage with Variable Size
2751 @cindex automatic freeing
2752 @cindex @code{alloca} function
2753 @cindex automatic storage with variable size
2755 The function @code{alloca} supports a kind of half-dynamic allocation in
2756 which blocks are allocated dynamically but freed automatically.
2758 Allocating a block with @code{alloca} is an explicit action; you can
2759 allocate as many blocks as you wish, and compute the size at run time.  But
2760 all the blocks are freed when you exit the function that @code{alloca} was
2761 called from, just as if they were automatic variables declared in that
2762 function.  There is no way to free the space explicitly.
2764 The prototype for @code{alloca} is in @file{stdlib.h}.  This function is
2765 a BSD extension.
2766 @pindex stdlib.h
2768 @comment stdlib.h
2769 @comment GNU, BSD
2770 @deftypefun {void *} alloca (size_t @var{size})
2771 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2772 The return value of @code{alloca} is the address of a block of @var{size}
2773 bytes of memory, allocated in the stack frame of the calling function.
2774 @end deftypefun
2776 Do not use @code{alloca} inside the arguments of a function call---you
2777 will get unpredictable results, because the stack space for the
2778 @code{alloca} would appear on the stack in the middle of the space for
2779 the function arguments.  An example of what to avoid is @code{foo (x,
2780 alloca (4), y)}.
2781 @c This might get fixed in future versions of GCC, but that won't make
2782 @c it safe with compilers generally.
2784 @menu
2785 * Alloca Example::              Example of using @code{alloca}.
2786 * Advantages of Alloca::        Reasons to use @code{alloca}.
2787 * Disadvantages of Alloca::     Reasons to avoid @code{alloca}.
2788 * GNU C Variable-Size Arrays::  Only in GNU C, here is an alternative
2789                                  method of allocating dynamically and
2790                                  freeing automatically.
2791 @end menu
2793 @node Alloca Example
2794 @subsubsection @code{alloca} Example
2796 As an example of the use of @code{alloca}, here is a function that opens
2797 a file name made from concatenating two argument strings, and returns a
2798 file descriptor or minus one signifying failure:
2800 @smallexample
2802 open2 (char *str1, char *str2, int flags, int mode)
2804   char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
2805   stpcpy (stpcpy (name, str1), str2);
2806   return open (name, flags, mode);
2808 @end smallexample
2810 @noindent
2811 Here is how you would get the same results with @code{malloc} and
2812 @code{free}:
2814 @smallexample
2816 open2 (char *str1, char *str2, int flags, int mode)
2818   char *name = (char *) malloc (strlen (str1) + strlen (str2) + 1);
2819   int desc;
2820   if (name == 0)
2821     fatal ("virtual memory exceeded");
2822   stpcpy (stpcpy (name, str1), str2);
2823   desc = open (name, flags, mode);
2824   free (name);
2825   return desc;
2827 @end smallexample
2829 As you can see, it is simpler with @code{alloca}.  But @code{alloca} has
2830 other, more important advantages, and some disadvantages.
2832 @node Advantages of Alloca
2833 @subsubsection Advantages of @code{alloca}
2835 Here are the reasons why @code{alloca} may be preferable to @code{malloc}:
2837 @itemize @bullet
2838 @item
2839 Using @code{alloca} wastes very little space and is very fast.  (It is
2840 open-coded by the GNU C compiler.)
2842 @item
2843 Since @code{alloca} does not have separate pools for different sizes of
2844 blocks, space used for any size block can be reused for any other size.
2845 @code{alloca} does not cause memory fragmentation.
2847 @item
2848 @cindex longjmp
2849 Nonlocal exits done with @code{longjmp} (@pxref{Non-Local Exits})
2850 automatically free the space allocated with @code{alloca} when they exit
2851 through the function that called @code{alloca}.  This is the most
2852 important reason to use @code{alloca}.
2854 To illustrate this, suppose you have a function
2855 @code{open_or_report_error} which returns a descriptor, like
2856 @code{open}, if it succeeds, but does not return to its caller if it
2857 fails.  If the file cannot be opened, it prints an error message and
2858 jumps out to the command level of your program using @code{longjmp}.
2859 Let's change @code{open2} (@pxref{Alloca Example}) to use this
2860 subroutine:@refill
2862 @smallexample
2864 open2 (char *str1, char *str2, int flags, int mode)
2866   char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
2867   stpcpy (stpcpy (name, str1), str2);
2868   return open_or_report_error (name, flags, mode);
2870 @end smallexample
2872 @noindent
2873 Because of the way @code{alloca} works, the memory it allocates is
2874 freed even when an error occurs, with no special effort required.
2876 By contrast, the previous definition of @code{open2} (which uses
2877 @code{malloc} and @code{free}) would develop a memory leak if it were
2878 changed in this way.  Even if you are willing to make more changes to
2879 fix it, there is no easy way to do so.
2880 @end itemize
2882 @node Disadvantages of Alloca
2883 @subsubsection Disadvantages of @code{alloca}
2885 @cindex @code{alloca} disadvantages
2886 @cindex disadvantages of @code{alloca}
2887 These are the disadvantages of @code{alloca} in comparison with
2888 @code{malloc}:
2890 @itemize @bullet
2891 @item
2892 If you try to allocate more memory than the machine can provide, you
2893 don't get a clean error message.  Instead you get a fatal signal like
2894 the one you would get from an infinite recursion; probably a
2895 segmentation violation (@pxref{Program Error Signals}).
2897 @item
2898 Some @nongnusystems{} fail to support @code{alloca}, so it is less
2899 portable.  However, a slower emulation of @code{alloca} written in C
2900 is available for use on systems with this deficiency.
2901 @end itemize
2903 @node GNU C Variable-Size Arrays
2904 @subsubsection GNU C Variable-Size Arrays
2905 @cindex variable-sized arrays
2907 In GNU C, you can replace most uses of @code{alloca} with an array of
2908 variable size.  Here is how @code{open2} would look then:
2910 @smallexample
2911 int open2 (char *str1, char *str2, int flags, int mode)
2913   char name[strlen (str1) + strlen (str2) + 1];
2914   stpcpy (stpcpy (name, str1), str2);
2915   return open (name, flags, mode);
2917 @end smallexample
2919 But @code{alloca} is not always equivalent to a variable-sized array, for
2920 several reasons:
2922 @itemize @bullet
2923 @item
2924 A variable size array's space is freed at the end of the scope of the
2925 name of the array.  The space allocated with @code{alloca}
2926 remains until the end of the function.
2928 @item
2929 It is possible to use @code{alloca} within a loop, allocating an
2930 additional block on each iteration.  This is impossible with
2931 variable-sized arrays.
2932 @end itemize
2934 @strong{NB:} If you mix use of @code{alloca} and variable-sized arrays
2935 within one function, exiting a scope in which a variable-sized array was
2936 declared frees all blocks allocated with @code{alloca} during the
2937 execution of that scope.
2940 @node Resizing the Data Segment
2941 @section Resizing the Data Segment
2943 The symbols in this section are declared in @file{unistd.h}.
2945 You will not normally use the functions in this section, because the
2946 functions described in @ref{Memory Allocation} are easier to use.  Those
2947 are interfaces to a @glibcadj{} memory allocator that uses the
2948 functions below itself.  The functions below are simple interfaces to
2949 system calls.
2951 @comment unistd.h
2952 @comment BSD
2953 @deftypefun int brk (void *@var{addr})
2954 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2956 @code{brk} sets the high end of the calling process' data segment to
2957 @var{addr}.
2959 The address of the end of a segment is defined to be the address of the
2960 last byte in the segment plus 1.
2962 The function has no effect if @var{addr} is lower than the low end of
2963 the data segment.  (This is considered success, by the way.)
2965 The function fails if it would cause the data segment to overlap another
2966 segment or exceed the process' data storage limit (@pxref{Limits on
2967 Resources}).
2969 The function is named for a common historical case where data storage
2970 and the stack are in the same segment.  Data storage allocation grows
2971 upward from the bottom of the segment while the stack grows downward
2972 toward it from the top of the segment and the curtain between them is
2973 called the @dfn{break}.
2975 The return value is zero on success.  On failure, the return value is
2976 @code{-1} and @code{errno} is set accordingly.  The following @code{errno}
2977 values are specific to this function:
2979 @table @code
2980 @item ENOMEM
2981 The request would cause the data segment to overlap another segment or
2982 exceed the process' data storage limit.
2983 @end table
2985 @c The Brk system call in Linux (as opposed to the GNU C Library function)
2986 @c is considerably different.  It always returns the new end of the data
2987 @c segment, whether it succeeds or fails.  The GNU C library Brk determines
2988 @c it's a failure if and only if the system call returns an address less
2989 @c than the address requested.
2991 @end deftypefun
2994 @comment unistd.h
2995 @comment BSD
2996 @deftypefun void *sbrk (ptrdiff_t @var{delta})
2997 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2999 This function is the same as @code{brk} except that you specify the new
3000 end of the data segment as an offset @var{delta} from the current end
3001 and on success the return value is the address of the resulting end of
3002 the data segment instead of zero.
3004 This means you can use @samp{sbrk(0)} to find out what the current end
3005 of the data segment is.
3007 @end deftypefun
3011 @node Locking Pages
3012 @section Locking Pages
3013 @cindex locking pages
3014 @cindex memory lock
3015 @cindex paging
3017 You can tell the system to associate a particular virtual memory page
3018 with a real page frame and keep it that way --- i.e., cause the page to
3019 be paged in if it isn't already and mark it so it will never be paged
3020 out and consequently will never cause a page fault.  This is called
3021 @dfn{locking} a page.
3023 The functions in this chapter lock and unlock the calling process'
3024 pages.
3026 @menu
3027 * Why Lock Pages::                Reasons to read this section.
3028 * Locked Memory Details::         Everything you need to know locked
3029                                     memory
3030 * Page Lock Functions::           Here's how to do it.
3031 @end menu
3033 @node Why Lock Pages
3034 @subsection Why Lock Pages
3036 Because page faults cause paged out pages to be paged in transparently,
3037 a process rarely needs to be concerned about locking pages.  However,
3038 there are two reasons people sometimes are:
3040 @itemize @bullet
3042 @item
3043 Speed.  A page fault is transparent only insofar as the process is not
3044 sensitive to how long it takes to do a simple memory access.  Time-critical
3045 processes, especially realtime processes, may not be able to wait or
3046 may not be able to tolerate variance in execution speed.
3047 @cindex realtime processing
3048 @cindex speed of execution
3050 A process that needs to lock pages for this reason probably also needs
3051 priority among other processes for use of the CPU.  @xref{Priority}.
3053 In some cases, the programmer knows better than the system's demand
3054 paging allocator which pages should remain in real memory to optimize
3055 system performance.  In this case, locking pages can help.
3057 @item
3058 Privacy.  If you keep secrets in virtual memory and that virtual memory
3059 gets paged out, that increases the chance that the secrets will get out.
3060 If a password gets written out to disk swap space, for example, it might
3061 still be there long after virtual and real memory have been wiped clean.
3063 @end itemize
3065 Be aware that when you lock a page, that's one fewer page frame that can
3066 be used to back other virtual memory (by the same or other processes),
3067 which can mean more page faults, which means the system runs more
3068 slowly.  In fact, if you lock enough memory, some programs may not be
3069 able to run at all for lack of real memory.
3071 @node Locked Memory Details
3072 @subsection Locked Memory Details
3074 A memory lock is associated with a virtual page, not a real frame.  The
3075 paging rule is: If a frame backs at least one locked page, don't page it
3076 out.
3078 Memory locks do not stack.  I.e., you can't lock a particular page twice
3079 so that it has to be unlocked twice before it is truly unlocked.  It is
3080 either locked or it isn't.
3082 A memory lock persists until the process that owns the memory explicitly
3083 unlocks it.  (But process termination and exec cause the virtual memory
3084 to cease to exist, which you might say means it isn't locked any more).
3086 Memory locks are not inherited by child processes.  (But note that on a
3087 modern Unix system, immediately after a fork, the parent's and the
3088 child's virtual address space are backed by the same real page frames,
3089 so the child enjoys the parent's locks).  @xref{Creating a Process}.
3091 Because of its ability to impact other processes, only the superuser can
3092 lock a page.  Any process can unlock its own page.
3094 The system sets limits on the amount of memory a process can have locked
3095 and the amount of real memory it can have dedicated to it.  @xref{Limits
3096 on Resources}.
3098 In Linux, locked pages aren't as locked as you might think.
3099 Two virtual pages that are not shared memory can nonetheless be backed
3100 by the same real frame.  The kernel does this in the name of efficiency
3101 when it knows both virtual pages contain identical data, and does it
3102 even if one or both of the virtual pages are locked.
3104 But when a process modifies one of those pages, the kernel must get it a
3105 separate frame and fill it with the page's data.  This is known as a
3106 @dfn{copy-on-write page fault}.  It takes a small amount of time and in
3107 a pathological case, getting that frame may require I/O.
3108 @cindex copy-on-write page fault
3109 @cindex page fault, copy-on-write
3111 To make sure this doesn't happen to your program, don't just lock the
3112 pages.  Write to them as well, unless you know you won't write to them
3113 ever.  And to make sure you have pre-allocated frames for your stack,
3114 enter a scope that declares a C automatic variable larger than the
3115 maximum stack size you will need, set it to something, then return from
3116 its scope.
3118 @node Page Lock Functions
3119 @subsection Functions To Lock And Unlock Pages
3121 The symbols in this section are declared in @file{sys/mman.h}.  These
3122 functions are defined by POSIX.1b, but their availability depends on
3123 your kernel.  If your kernel doesn't allow these functions, they exist
3124 but always fail.  They @emph{are} available with a Linux kernel.
3126 @strong{Portability Note:} POSIX.1b requires that when the @code{mlock}
3127 and @code{munlock} functions are available, the file @file{unistd.h}
3128 define the macro @code{_POSIX_MEMLOCK_RANGE} and the file
3129 @code{limits.h} define the macro @code{PAGESIZE} to be the size of a
3130 memory page in bytes.  It requires that when the @code{mlockall} and
3131 @code{munlockall} functions are available, the @file{unistd.h} file
3132 define the macro @code{_POSIX_MEMLOCK}.  @Theglibc{} conforms to
3133 this requirement.
3135 @comment sys/mman.h
3136 @comment POSIX.1b
3137 @deftypefun int mlock (const void *@var{addr}, size_t @var{len})
3138 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3140 @code{mlock} locks a range of the calling process' virtual pages.
3142 The range of memory starts at address @var{addr} and is @var{len} bytes
3143 long.  Actually, since you must lock whole pages, it is the range of
3144 pages that include any part of the specified range.
3146 When the function returns successfully, each of those pages is backed by
3147 (connected to) a real frame (is resident) and is marked to stay that
3148 way.  This means the function may cause page-ins and have to wait for
3149 them.
3151 When the function fails, it does not affect the lock status of any
3152 pages.
3154 The return value is zero if the function succeeds.  Otherwise, it is
3155 @code{-1} and @code{errno} is set accordingly.  @code{errno} values
3156 specific to this function are:
3158 @table @code
3159 @item ENOMEM
3160 @itemize @bullet
3161 @item
3162 At least some of the specified address range does not exist in the
3163 calling process' virtual address space.
3164 @item
3165 The locking would cause the process to exceed its locked page limit.
3166 @end itemize
3168 @item EPERM
3169 The calling process is not superuser.
3171 @item EINVAL
3172 @var{len} is not positive.
3174 @item ENOSYS
3175 The kernel does not provide @code{mlock} capability.
3177 @end table
3179 You can lock @emph{all} a process' memory with @code{mlockall}.  You
3180 unlock memory with @code{munlock} or @code{munlockall}.
3182 To avoid all page faults in a C program, you have to use
3183 @code{mlockall}, because some of the memory a program uses is hidden
3184 from the C code, e.g. the stack and automatic variables, and you
3185 wouldn't know what address to tell @code{mlock}.
3187 @end deftypefun
3189 @comment sys/mman.h
3190 @comment POSIX.1b
3191 @deftypefun int munlock (const void *@var{addr}, size_t @var{len})
3192 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3194 @code{munlock} unlocks a range of the calling process' virtual pages.
3196 @code{munlock} is the inverse of @code{mlock} and functions completely
3197 analogously to @code{mlock}, except that there is no @code{EPERM}
3198 failure.
3200 @end deftypefun
3202 @comment sys/mman.h
3203 @comment POSIX.1b
3204 @deftypefun int mlockall (int @var{flags})
3205 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3207 @code{mlockall} locks all the pages in a process' virtual memory address
3208 space, and/or any that are added to it in the future.  This includes the
3209 pages of the code, data and stack segment, as well as shared libraries,
3210 user space kernel data, shared memory, and memory mapped files.
3212 @var{flags} is a string of single bit flags represented by the following
3213 macros.  They tell @code{mlockall} which of its functions you want.  All
3214 other bits must be zero.
3216 @vtable @code
3218 @item MCL_CURRENT
3219 Lock all pages which currently exist in the calling process' virtual
3220 address space.
3222 @item MCL_FUTURE
3223 Set a mode such that any pages added to the process' virtual address
3224 space in the future will be locked from birth.  This mode does not
3225 affect future address spaces owned by the same process so exec, which
3226 replaces a process' address space, wipes out @code{MCL_FUTURE}.
3227 @xref{Executing a File}.
3229 @end vtable
3231 When the function returns successfully, and you specified
3232 @code{MCL_CURRENT}, all of the process' pages are backed by (connected
3233 to) real frames (they are resident) and are marked to stay that way.
3234 This means the function may cause page-ins and have to wait for them.
3236 When the process is in @code{MCL_FUTURE} mode because it successfully
3237 executed this function and specified @code{MCL_CURRENT}, any system call
3238 by the process that requires space be added to its virtual address space
3239 fails with @code{errno} = @code{ENOMEM} if locking the additional space
3240 would cause the process to exceed its locked page limit.  In the case
3241 that the address space addition that can't be accommodated is stack
3242 expansion, the stack expansion fails and the kernel sends a
3243 @code{SIGSEGV} signal to the process.
3245 When the function fails, it does not affect the lock status of any pages
3246 or the future locking mode.
3248 The return value is zero if the function succeeds.  Otherwise, it is
3249 @code{-1} and @code{errno} is set accordingly.  @code{errno} values
3250 specific to this function are:
3252 @table @code
3253 @item ENOMEM
3254 @itemize @bullet
3255 @item
3256 At least some of the specified address range does not exist in the
3257 calling process' virtual address space.
3258 @item
3259 The locking would cause the process to exceed its locked page limit.
3260 @end itemize
3262 @item EPERM
3263 The calling process is not superuser.
3265 @item EINVAL
3266 Undefined bits in @var{flags} are not zero.
3268 @item ENOSYS
3269 The kernel does not provide @code{mlockall} capability.
3271 @end table
3273 You can lock just specific pages with @code{mlock}.  You unlock pages
3274 with @code{munlockall} and @code{munlock}.
3276 @end deftypefun
3279 @comment sys/mman.h
3280 @comment POSIX.1b
3281 @deftypefun int munlockall (void)
3282 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3284 @code{munlockall} unlocks every page in the calling process' virtual
3285 address space and turns off @code{MCL_FUTURE} future locking mode.
3287 The return value is zero if the function succeeds.  Otherwise, it is
3288 @code{-1} and @code{errno} is set accordingly.  The only way this
3289 function can fail is for generic reasons that all functions and system
3290 calls can fail, so there are no specific @code{errno} values.
3292 @end deftypefun
3297 @ignore
3298 @c This was never actually implemented.  -zw
3299 @node Relocating Allocator
3300 @section Relocating Allocator
3302 @cindex relocating memory allocator
3303 Any system of dynamic memory allocation has overhead: the amount of
3304 space it uses is more than the amount the program asks for.  The
3305 @dfn{relocating memory allocator} achieves very low overhead by moving
3306 blocks in memory as necessary, on its own initiative.
3308 @c @menu
3309 @c * Relocator Concepts::               How to understand relocating allocation.
3310 @c * Using Relocator::          Functions for relocating allocation.
3311 @c @end menu
3313 @node Relocator Concepts
3314 @subsection Concepts of Relocating Allocation
3316 @ifinfo
3317 The @dfn{relocating memory allocator} achieves very low overhead by
3318 moving blocks in memory as necessary, on its own initiative.
3319 @end ifinfo
3321 When you allocate a block with @code{malloc}, the address of the block
3322 never changes unless you use @code{realloc} to change its size.  Thus,
3323 you can safely store the address in various places, temporarily or
3324 permanently, as you like.  This is not safe when you use the relocating
3325 memory allocator, because any and all relocatable blocks can move
3326 whenever you allocate memory in any fashion.  Even calling @code{malloc}
3327 or @code{realloc} can move the relocatable blocks.
3329 @cindex handle
3330 For each relocatable block, you must make a @dfn{handle}---a pointer
3331 object in memory, designated to store the address of that block.  The
3332 relocating allocator knows where each block's handle is, and updates the
3333 address stored there whenever it moves the block, so that the handle
3334 always points to the block.  Each time you access the contents of the
3335 block, you should fetch its address anew from the handle.
3337 To call any of the relocating allocator functions from a signal handler
3338 is almost certainly incorrect, because the signal could happen at any
3339 time and relocate all the blocks.  The only way to make this safe is to
3340 block the signal around any access to the contents of any relocatable
3341 block---not a convenient mode of operation.  @xref{Nonreentrancy}.
3343 @node Using Relocator
3344 @subsection Allocating and Freeing Relocatable Blocks
3346 @pindex malloc.h
3347 In the descriptions below, @var{handleptr} designates the address of the
3348 handle.  All the functions are declared in @file{malloc.h}; all are GNU
3349 extensions.
3351 @comment malloc.h
3352 @comment GNU
3353 @c @deftypefun {void *} r_alloc (void **@var{handleptr}, size_t @var{size})
3354 This function allocates a relocatable block of size @var{size}.  It
3355 stores the block's address in @code{*@var{handleptr}} and returns
3356 a non-null pointer to indicate success.
3358 If @code{r_alloc} can't get the space needed, it stores a null pointer
3359 in @code{*@var{handleptr}}, and returns a null pointer.
3360 @end deftypefun
3362 @comment malloc.h
3363 @comment GNU
3364 @c @deftypefun void r_alloc_free (void **@var{handleptr})
3365 This function is the way to free a relocatable block.  It frees the
3366 block that @code{*@var{handleptr}} points to, and stores a null pointer
3367 in @code{*@var{handleptr}} to show it doesn't point to an allocated
3368 block any more.
3369 @end deftypefun
3371 @comment malloc.h
3372 @comment GNU
3373 @c @deftypefun {void *} r_re_alloc (void **@var{handleptr}, size_t @var{size})
3374 The function @code{r_re_alloc} adjusts the size of the block that
3375 @code{*@var{handleptr}} points to, making it @var{size} bytes long.  It
3376 stores the address of the resized block in @code{*@var{handleptr}} and
3377 returns a non-null pointer to indicate success.
3379 If enough memory is not available, this function returns a null pointer
3380 and does not modify @code{*@var{handleptr}}.
3381 @end deftypefun
3382 @end ignore
3387 @ignore
3388 @comment No longer available...
3390 @comment @node Memory Warnings
3391 @comment @section Memory Usage Warnings
3392 @comment @cindex memory usage warnings
3393 @comment @cindex warnings of memory almost full
3395 @pindex malloc.c
3396 You can ask for warnings as the program approaches running out of memory
3397 space, by calling @code{memory_warnings}.  This tells @code{malloc} to
3398 check memory usage every time it asks for more memory from the operating
3399 system.  This is a GNU extension declared in @file{malloc.h}.
3401 @comment malloc.h
3402 @comment GNU
3403 @comment @deftypefun void memory_warnings (void *@var{start}, void (*@var{warn-func}) (const char *))
3404 Call this function to request warnings for nearing exhaustion of virtual
3405 memory.
3407 The argument @var{start} says where data space begins, in memory.  The
3408 allocator compares this against the last address used and against the
3409 limit of data space, to determine the fraction of available memory in
3410 use.  If you supply zero for @var{start}, then a default value is used
3411 which is right in most circumstances.
3413 For @var{warn-func}, supply a function that @code{malloc} can call to
3414 warn you.  It is called with a string (a warning message) as argument.
3415 Normally it ought to display the string for the user to read.
3416 @end deftypefun
3418 The warnings come when memory becomes 75% full, when it becomes 85%
3419 full, and when it becomes 95% full.  Above 95% you get another warning
3420 each time memory usage increases.
3422 @end ignore