Add femode_t functions: sh.
[glibc.git] / manual / memory.texi
blob53831053dd9e3559c5a92f4a8471124c9b7b14b9
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 * Unconstrained Allocation::    The @code{malloc} facility allows fully general
166                                  dynamic allocation.
167 * Allocation Debugging::        Finding memory leaks and not freed memory.
168 * Obstacks::                    Obstacks are less general than malloc
169                                  but more efficient and convenient.
170 * Variable Size Automatic::     Allocation of variable-sized blocks
171                                  of automatic storage that are freed when the
172                                  calling function returns.
173 @end menu
176 @node Memory Allocation and C
177 @subsection Memory Allocation in C Programs
179 The C language supports two kinds of memory allocation through the
180 variables in C programs:
182 @itemize @bullet
183 @item
184 @dfn{Static allocation} is what happens when you declare a static or
185 global variable.  Each static or global variable defines one block of
186 space, of a fixed size.  The space is allocated once, when your program
187 is started (part of the exec operation), and is never freed.
188 @cindex static memory allocation
189 @cindex static storage class
191 @item
192 @dfn{Automatic allocation} happens when you declare an automatic
193 variable, such as a function argument or a local variable.  The space
194 for an automatic variable is allocated when the compound statement
195 containing the declaration is entered, and is freed when that
196 compound statement is exited.
197 @cindex automatic memory allocation
198 @cindex automatic storage class
200 In GNU C, the size of the automatic storage can be an expression
201 that varies.  In other C implementations, it must be a constant.
202 @end itemize
204 A third important kind of memory allocation, @dfn{dynamic allocation},
205 is not supported by C variables but is available via @glibcadj{}
206 functions.
207 @cindex dynamic memory allocation
209 @subsubsection Dynamic Memory Allocation
210 @cindex dynamic memory allocation
212 @dfn{Dynamic memory allocation} is a technique in which programs
213 determine as they are running where to store some information.  You need
214 dynamic allocation when the amount of memory you need, or how long you
215 continue to need it, depends on factors that are not known before the
216 program runs.
218 For example, you may need a block to store a line read from an input
219 file; since there is no limit to how long a line can be, you must
220 allocate the memory dynamically and make it dynamically larger as you
221 read more of the line.
223 Or, you may need a block for each record or each definition in the input
224 data; since you can't know in advance how many there will be, you must
225 allocate a new block for each record or definition as you read it.
227 When you use dynamic allocation, the allocation of a block of memory is
228 an action that the program requests explicitly.  You call a function or
229 macro when you want to allocate space, and specify the size with an
230 argument.  If you want to free the space, you do so by calling another
231 function or macro.  You can do these things whenever you want, as often
232 as you want.
234 Dynamic allocation is not supported by C variables; there is no storage
235 class ``dynamic'', and there can never be a C variable whose value is
236 stored in dynamically allocated space.  The only way to get dynamically
237 allocated memory is via a system call (which is generally via a @glibcadj{}
238 function call), and the only way to refer to dynamically
239 allocated space is through a pointer.  Because it is less convenient,
240 and because the actual process of dynamic allocation requires more
241 computation time, programmers generally use dynamic allocation only when
242 neither static nor automatic allocation will serve.
244 For example, if you want to allocate dynamically some space to hold a
245 @code{struct foobar}, you cannot declare a variable of type @code{struct
246 foobar} whose contents are the dynamically allocated space.  But you can
247 declare a variable of pointer type @code{struct foobar *} and assign it the
248 address of the space.  Then you can use the operators @samp{*} and
249 @samp{->} on this pointer variable to refer to the contents of the space:
251 @smallexample
253   struct foobar *ptr
254      = (struct foobar *) malloc (sizeof (struct foobar));
255   ptr->name = x;
256   ptr->next = current_foobar;
257   current_foobar = ptr;
259 @end smallexample
261 @node Unconstrained Allocation
262 @subsection Unconstrained Allocation
263 @cindex unconstrained memory allocation
264 @cindex @code{malloc} function
265 @cindex heap, dynamic allocation from
267 The most general dynamic allocation facility is @code{malloc}.  It
268 allows you to allocate blocks of memory of any size at any time, make
269 them bigger or smaller at any time, and free the blocks individually at
270 any time (or never).
272 @menu
273 * Basic Allocation::            Simple use of @code{malloc}.
274 * Malloc Examples::             Examples of @code{malloc}.  @code{xmalloc}.
275 * Freeing after Malloc::        Use @code{free} to free a block you
276                                  got with @code{malloc}.
277 * Changing Block Size::         Use @code{realloc} to make a block
278                                  bigger or smaller.
279 * Allocating Cleared Space::    Use @code{calloc} to allocate a
280                                  block and clear it.
281 * Efficiency and Malloc::       Efficiency considerations in use of
282                                  these functions.
283 * Aligned Memory Blocks::       Allocating specially aligned memory.
284 * Malloc Tunable Parameters::   Use @code{mallopt} to adjust allocation
285                                  parameters.
286 * Heap Consistency Checking::   Automatic checking for errors.
287 * Hooks for Malloc::            You can use these hooks for debugging
288                                  programs that use @code{malloc}.
289 * Statistics of Malloc::        Getting information about how much
290                                  memory your program is using.
291 * Summary of Malloc::           Summary of @code{malloc} and related functions.
292 @end menu
294 @node Basic Allocation
295 @subsubsection Basic Memory Allocation
296 @cindex allocation of memory with @code{malloc}
298 To allocate a block of memory, call @code{malloc}.  The prototype for
299 this function is in @file{stdlib.h}.
300 @pindex stdlib.h
302 @comment malloc.h stdlib.h
303 @comment ISO
304 @deftypefun {void *} malloc (size_t @var{size})
305 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
306 @c Malloc hooks and __morecore pointers, as well as such parameters as
307 @c max_n_mmaps and max_mmapped_mem, are accessed without guards, so they
308 @c could pose a thread safety issue; in order to not declare malloc
309 @c MT-unsafe, it's modifying the hooks and parameters while multiple
310 @c threads are active that is regarded as unsafe.  An arena's next field
311 @c is initialized and never changed again, except for main_arena's,
312 @c that's protected by list_lock; next_free is only modified while
313 @c list_lock is held too.  All other data members of an arena, as well
314 @c as the metadata of the memory areas assigned to it, are only modified
315 @c while holding the arena's mutex (fastbin pointers use catomic ops
316 @c because they may be modified by free without taking the arena's
317 @c lock).  Some reassurance was needed for fastbins, for it wasn't clear
318 @c how they were initialized.  It turns out they are always
319 @c zero-initialized: main_arena's, for being static data, and other
320 @c arena's, for being just-mmapped memory.
322 @c Leaking file descriptors and memory in case of cancellation is
323 @c unavoidable without disabling cancellation, but the lock situation is
324 @c a bit more complicated: we don't have fallback arenas for malloc to
325 @c be safe to call from within signal handlers.  Error-checking mutexes
326 @c or trylock could enable us to try and use alternate arenas, even with
327 @c -DPER_THREAD (enabled by default), but supporting interruption
328 @c (cancellation or signal handling) while holding the arena list mutex
329 @c would require more work; maybe blocking signals and disabling async
330 @c cancellation while manipulating the arena lists?
332 @c __libc_malloc @asulock @aculock @acsfd @acsmem
333 @c  force_reg ok
334 @c  *malloc_hook unguarded
335 @c  arena_lock @asulock @aculock @acsfd @acsmem
336 @c   mutex_lock @asulock @aculock
337 @c   arena_get2 @asulock @aculock @acsfd @acsmem
338 @c    get_free_list @asulock @aculock
339 @c     mutex_lock (list_lock) dup @asulock @aculock
340 @c     mutex_unlock (list_lock) dup @aculock
341 @c     mutex_lock (arena lock) dup @asulock @aculock [returns locked]
342 @c    __get_nprocs ext ok @acsfd
343 @c    NARENAS_FROM_NCORES ok
344 @c    catomic_compare_and_exchange_bool_acq ok
345 @c    _int_new_arena ok @asulock @aculock @acsmem
346 @c     new_heap ok @acsmem
347 @c      mmap ok @acsmem
348 @c      munmap ok @acsmem
349 @c      mprotect ok
350 @c     chunk2mem ok
351 @c     set_head ok
352 @c     tsd_setspecific dup ok
353 @c     mutex_init ok
354 @c     mutex_lock (just-created mutex) ok, returns locked
355 @c     mutex_lock (list_lock) dup @asulock @aculock
356 @c     atomic_write_barrier ok
357 @c     mutex_unlock (list_lock) @aculock
358 @c    catomic_decrement ok
359 @c    reused_arena @asulock @aculock
360 @c      reads&writes next_to_use and iterates over arena next without guards
361 @c      those are harmless as long as we don't drop arenas from the
362 @c      NEXT list, and we never do; when a thread terminates,
363 @c      arena_thread_freeres prepends the arena to the free_list
364 @c      NEXT_FREE list, but NEXT is never modified, so it's safe!
365 @c     mutex_trylock (arena lock) @asulock @aculock
366 @c     mutex_lock (arena lock) dup @asulock @aculock
367 @c     tsd_setspecific dup ok
368 @c  _int_malloc @acsfd @acsmem
369 @c   checked_request2size ok
370 @c    REQUEST_OUT_OF_RANGE ok
371 @c    request2size ok
372 @c   get_max_fast ok
373 @c   fastbin_index ok
374 @c   fastbin ok
375 @c   catomic_compare_and_exhange_val_acq ok
376 @c   malloc_printerr dup @mtsenv
377 @c     if we get to it, we're toast already, undefined behavior must have
378 @c     been invoked before
379 @c    libc_message @mtsenv [no leaks with cancellation disabled]
380 @c     FATAL_PREPARE ok
381 @c      pthread_setcancelstate disable ok
382 @c     libc_secure_getenv @mtsenv
383 @c      getenv @mtsenv
384 @c     open_not_cancel_2 dup @acsfd
385 @c     strchrnul ok
386 @c     WRITEV_FOR_FATAL ok
387 @c      writev ok
388 @c     mmap ok @acsmem
389 @c     munmap ok @acsmem
390 @c     BEFORE_ABORT @acsfd
391 @c      backtrace ok
392 @c      write_not_cancel dup ok
393 @c      backtrace_symbols_fd @aculock
394 @c      open_not_cancel_2 dup @acsfd
395 @c      read_not_cancel dup ok
396 @c      close_not_cancel_no_status dup @acsfd
397 @c     abort ok
398 @c    itoa_word ok
399 @c    abort ok
400 @c   check_remalloced_chunk ok/disabled
401 @c   chunk2mem dup ok
402 @c   alloc_perturb ok
403 @c   in_smallbin_range ok
404 @c   smallbin_index ok
405 @c   bin_at ok
406 @c   last ok
407 @c   malloc_consolidate ok
408 @c    get_max_fast dup ok
409 @c    clear_fastchunks ok
410 @c    unsorted_chunks dup ok
411 @c    fastbin dup ok
412 @c    atomic_exchange_acq ok
413 @c    check_inuse_chunk dup ok/disabled
414 @c    chunk_at_offset dup ok
415 @c    chunksize dup ok
416 @c    inuse_bit_at_offset dup ok
417 @c    unlink dup ok
418 @c    clear_inuse_bit_at_offset dup ok
419 @c    in_smallbin_range dup ok
420 @c    set_head dup ok
421 @c    malloc_init_state ok
422 @c     bin_at dup ok
423 @c     set_noncontiguous dup ok
424 @c     set_max_fast dup ok
425 @c     initial_top ok
426 @c      unsorted_chunks dup ok
427 @c    check_malloc_state ok/disabled
428 @c   set_inuse_bit_at_offset ok
429 @c   check_malloced_chunk ok/disabled
430 @c   largebin_index ok
431 @c   have_fastchunks ok
432 @c   unsorted_chunks ok
433 @c    bin_at ok
434 @c   chunksize ok
435 @c   chunk_at_offset ok
436 @c   set_head ok
437 @c   set_foot ok
438 @c   mark_bin ok
439 @c    idx2bit ok
440 @c   first ok
441 @c   unlink ok
442 @c    malloc_printerr dup ok
443 @c    in_smallbin_range dup ok
444 @c   idx2block ok
445 @c   idx2bit dup ok
446 @c   next_bin ok
447 @c   sysmalloc @acsfd @acsmem
448 @c    MMAP @acsmem
449 @c    set_head dup ok
450 @c    check_chunk ok/disabled
451 @c    chunk2mem dup ok
452 @c    chunksize dup ok
453 @c    chunk_at_offset dup ok
454 @c    heap_for_ptr ok
455 @c    grow_heap ok
456 @c     mprotect ok
457 @c    set_head dup ok
458 @c    new_heap @acsmem
459 @c     MMAP dup @acsmem
460 @c     munmap @acsmem
461 @c    top ok
462 @c    set_foot dup ok
463 @c    contiguous ok
464 @c    MORECORE ok
465 @c     *__morecore ok unguarded
466 @c      __default_morecore
467 @c       sbrk ok
468 @c    force_reg dup ok
469 @c    *__after_morecore_hook unguarded
470 @c    set_noncontiguous ok
471 @c    malloc_printerr dup ok
472 @c    _int_free (have_lock) @acsfd @acsmem [@asulock @aculock]
473 @c     chunksize dup ok
474 @c     mutex_unlock dup @aculock/!have_lock
475 @c     malloc_printerr dup ok
476 @c     check_inuse_chunk ok/disabled
477 @c     chunk_at_offset dup ok
478 @c     mutex_lock dup @asulock @aculock/@have_lock
479 @c     chunk2mem dup ok
480 @c     free_perturb ok
481 @c     set_fastchunks ok
482 @c      catomic_and ok
483 @c     fastbin_index dup ok
484 @c     fastbin dup ok
485 @c     catomic_compare_and_exchange_val_rel ok
486 @c     chunk_is_mmapped ok
487 @c     contiguous dup ok
488 @c     prev_inuse ok
489 @c     unlink dup ok
490 @c     inuse_bit_at_offset dup ok
491 @c     clear_inuse_bit_at_offset ok
492 @c     unsorted_chunks dup ok
493 @c     in_smallbin_range dup ok
494 @c     set_head dup ok
495 @c     set_foot dup ok
496 @c     check_free_chunk ok/disabled
497 @c     check_chunk dup ok/disabled
498 @c     have_fastchunks dup ok
499 @c     malloc_consolidate dup ok
500 @c     systrim ok
501 @c      MORECORE dup ok
502 @c      *__after_morecore_hook dup unguarded
503 @c      set_head dup ok
504 @c      check_malloc_state ok/disabled
505 @c     top dup ok
506 @c     heap_for_ptr dup ok
507 @c     heap_trim @acsfd @acsmem
508 @c      top dup ok
509 @c      chunk_at_offset dup ok
510 @c      prev_chunk ok
511 @c      chunksize dup ok
512 @c      prev_inuse dup ok
513 @c      delete_heap @acsmem
514 @c       munmap dup @acsmem
515 @c      unlink dup ok
516 @c      set_head dup ok
517 @c      shrink_heap @acsfd
518 @c       check_may_shrink_heap @acsfd
519 @c        open_not_cancel_2 @acsfd
520 @c        read_not_cancel ok
521 @c        close_not_cancel_no_status @acsfd
522 @c       MMAP dup ok
523 @c       madvise ok
524 @c     munmap_chunk @acsmem
525 @c      chunksize dup ok
526 @c      chunk_is_mmapped dup ok
527 @c      chunk2mem dup ok
528 @c      malloc_printerr dup ok
529 @c      munmap dup @acsmem
530 @c    check_malloc_state ok/disabled
531 @c  arena_get_retry @asulock @aculock @acsfd @acsmem
532 @c   mutex_unlock dup @aculock
533 @c   mutex_lock dup @asulock @aculock
534 @c   arena_get2 dup @asulock @aculock @acsfd @acsmem
535 @c  mutex_unlock @aculock
536 @c  mem2chunk ok
537 @c  chunk_is_mmapped ok
538 @c  arena_for_chunk ok
539 @c   chunk_non_main_arena ok
540 @c   heap_for_ptr ok
541 This function returns a pointer to a newly allocated block @var{size}
542 bytes long, or a null pointer if the block could not be allocated.
543 @end deftypefun
545 The contents of the block are undefined; you must initialize it yourself
546 (or use @code{calloc} instead; @pxref{Allocating Cleared Space}).
547 Normally you would cast the value as a pointer to the kind of object
548 that you want to store in the block.  Here we show an example of doing
549 so, and of initializing the space with zeros using the library function
550 @code{memset} (@pxref{Copying Strings and Arrays}):
552 @smallexample
553 struct foo *ptr;
554 @dots{}
555 ptr = (struct foo *) malloc (sizeof (struct foo));
556 if (ptr == 0) abort ();
557 memset (ptr, 0, sizeof (struct foo));
558 @end smallexample
560 You can store the result of @code{malloc} into any pointer variable
561 without a cast, because @w{ISO C} automatically converts the type
562 @code{void *} to another type of pointer when necessary.  But the cast
563 is necessary in contexts other than assignment operators or if you might
564 want your code to run in traditional C.
566 Remember that when allocating space for a string, the argument to
567 @code{malloc} must be one plus the length of the string.  This is
568 because a string is terminated with a null character that doesn't count
569 in the ``length'' of the string but does need space.  For example:
571 @smallexample
572 char *ptr;
573 @dots{}
574 ptr = (char *) malloc (length + 1);
575 @end smallexample
577 @noindent
578 @xref{Representation of Strings}, for more information about this.
580 @node Malloc Examples
581 @subsubsection Examples of @code{malloc}
583 If no more space is available, @code{malloc} returns a null pointer.
584 You should check the value of @emph{every} call to @code{malloc}.  It is
585 useful to write a subroutine that calls @code{malloc} and reports an
586 error if the value is a null pointer, returning only if the value is
587 nonzero.  This function is conventionally called @code{xmalloc}.  Here
588 it is:
590 @smallexample
591 void *
592 xmalloc (size_t size)
594   void *value = malloc (size);
595   if (value == 0)
596     fatal ("virtual memory exhausted");
597   return value;
599 @end smallexample
601 Here is a real example of using @code{malloc} (by way of @code{xmalloc}).
602 The function @code{savestring} will copy a sequence of characters into
603 a newly allocated null-terminated string:
605 @smallexample
606 @group
607 char *
608 savestring (const char *ptr, size_t len)
610   char *value = (char *) xmalloc (len + 1);
611   value[len] = '\0';
612   return (char *) memcpy (value, ptr, len);
614 @end group
615 @end smallexample
617 The block that @code{malloc} gives you is guaranteed to be aligned so
618 that it can hold any type of data.  On @gnusystems{}, the address is
619 always a multiple of eight on 32-bit systems, and a multiple of 16 on
620 64-bit systems.  Only rarely is any higher boundary (such as a page
621 boundary) necessary; for those cases, use @code{aligned_alloc} or
622 @code{posix_memalign} (@pxref{Aligned Memory Blocks}).
624 Note that the memory located after the end of the block is likely to be
625 in use for something else; perhaps a block already allocated by another
626 call to @code{malloc}.  If you attempt to treat the block as longer than
627 you asked for it to be, you are liable to destroy the data that
628 @code{malloc} uses to keep track of its blocks, or you may destroy the
629 contents of another block.  If you have already allocated a block and
630 discover you want it to be bigger, use @code{realloc} (@pxref{Changing
631 Block Size}).
633 @node Freeing after Malloc
634 @subsubsection Freeing Memory Allocated with @code{malloc}
635 @cindex freeing memory allocated with @code{malloc}
636 @cindex heap, freeing memory from
638 When you no longer need a block that you got with @code{malloc}, use the
639 function @code{free} to make the block available to be allocated again.
640 The prototype for this function is in @file{stdlib.h}.
641 @pindex stdlib.h
643 @comment malloc.h stdlib.h
644 @comment ISO
645 @deftypefun void free (void *@var{ptr})
646 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
647 @c __libc_free @asulock @aculock @acsfd @acsmem
648 @c   releasing memory into fastbins modifies the arena without taking
649 @c   its mutex, but catomic operations ensure safety.  If two (or more)
650 @c   threads are running malloc and have their own arenas locked when
651 @c   each gets a signal whose handler free()s large (non-fastbin-able)
652 @c   blocks from each other's arena, we deadlock; this is a more general
653 @c   case of @asulock.
654 @c  *__free_hook unguarded
655 @c  mem2chunk ok
656 @c  chunk_is_mmapped ok, chunk bits not modified after allocation
657 @c  chunksize ok
658 @c  munmap_chunk dup @acsmem
659 @c  arena_for_chunk dup ok
660 @c  _int_free (!have_lock) dup @asulock @aculock @acsfd @acsmem
661 The @code{free} function deallocates the block of memory pointed at
662 by @var{ptr}.
663 @end deftypefun
665 @comment stdlib.h
666 @comment Sun
667 @deftypefun void cfree (void *@var{ptr})
668 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
669 @c alias to free
670 This function does the same thing as @code{free}.  It's provided for
671 backward compatibility with SunOS; you should use @code{free} instead.
672 @end deftypefun
674 Freeing a block alters the contents of the block.  @strong{Do not expect to
675 find any data (such as a pointer to the next block in a chain of blocks) in
676 the block after freeing it.}  Copy whatever you need out of the block before
677 freeing it!  Here is an example of the proper way to free all the blocks in
678 a chain, and the strings that they point to:
680 @smallexample
681 struct chain
682   @{
683     struct chain *next;
684     char *name;
685   @}
687 void
688 free_chain (struct chain *chain)
690   while (chain != 0)
691     @{
692       struct chain *next = chain->next;
693       free (chain->name);
694       free (chain);
695       chain = next;
696     @}
698 @end smallexample
700 Occasionally, @code{free} can actually return memory to the operating
701 system and make the process smaller.  Usually, all it can do is allow a
702 later call to @code{malloc} to reuse the space.  In the meantime, the
703 space remains in your program as part of a free-list used internally by
704 @code{malloc}.
706 There is no point in freeing blocks at the end of a program, because all
707 of the program's space is given back to the system when the process
708 terminates.
710 @node Changing Block Size
711 @subsubsection Changing the Size of a Block
712 @cindex changing the size of a block (@code{malloc})
714 Often you do not know for certain how big a block you will ultimately need
715 at the time you must begin to use the block.  For example, the block might
716 be a buffer that you use to hold a line being read from a file; no matter
717 how long you make the buffer initially, you may encounter a line that is
718 longer.
720 You can make the block longer by calling @code{realloc}.  This function
721 is declared in @file{stdlib.h}.
722 @pindex stdlib.h
724 @comment malloc.h stdlib.h
725 @comment ISO
726 @deftypefun {void *} realloc (void *@var{ptr}, size_t @var{newsize})
727 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
728 @c It may call the implementations of malloc and free, so all of their
729 @c issues arise, plus the realloc hook, also accessed without guards.
731 @c __libc_realloc @asulock @aculock @acsfd @acsmem
732 @c  *__realloc_hook unguarded
733 @c  __libc_free dup @asulock @aculock @acsfd @acsmem
734 @c  __libc_malloc dup @asulock @aculock @acsfd @acsmem
735 @c  mem2chunk dup ok
736 @c  chunksize dup ok
737 @c  malloc_printerr dup ok
738 @c  checked_request2size dup ok
739 @c  chunk_is_mmapped dup ok
740 @c  mremap_chunk
741 @c   chunksize dup ok
742 @c   __mremap ok
743 @c   set_head dup ok
744 @c  MALLOC_COPY ok
745 @c   memcpy ok
746 @c  munmap_chunk dup @acsmem
747 @c  arena_for_chunk dup ok
748 @c  mutex_lock (arena mutex) dup @asulock @aculock
749 @c  _int_realloc @acsfd @acsmem
750 @c   malloc_printerr dup ok
751 @c   check_inuse_chunk dup ok/disabled
752 @c   chunk_at_offset dup ok
753 @c   chunksize dup ok
754 @c   set_head_size dup ok
755 @c   chunk_at_offset dup ok
756 @c   set_head dup ok
757 @c   chunk2mem dup ok
758 @c   inuse dup ok
759 @c   unlink dup ok
760 @c   _int_malloc dup @acsfd @acsmem
761 @c   mem2chunk dup ok
762 @c   MALLOC_COPY dup ok
763 @c   _int_free (have_lock) dup @acsfd @acsmem
764 @c   set_inuse_bit_at_offset dup ok
765 @c   set_head dup ok
766 @c  mutex_unlock (arena mutex) dup @aculock
767 @c  _int_free (!have_lock) dup @asulock @aculock @acsfd @acsmem
769 The @code{realloc} function changes the size of the block whose address is
770 @var{ptr} to be @var{newsize}.
772 Since the space after the end of the block may be in use, @code{realloc}
773 may find it necessary to copy the block to a new address where more free
774 space is available.  The value of @code{realloc} is the new address of the
775 block.  If the block needs to be moved, @code{realloc} copies the old
776 contents.
778 If you pass a null pointer for @var{ptr}, @code{realloc} behaves just
779 like @samp{malloc (@var{newsize})}.  This can be convenient, but beware
780 that older implementations (before @w{ISO C}) may not support this
781 behavior, and will probably crash when @code{realloc} is passed a null
782 pointer.
783 @end deftypefun
785 Like @code{malloc}, @code{realloc} may return a null pointer if no
786 memory space is available to make the block bigger.  When this happens,
787 the original block is untouched; it has not been modified or relocated.
789 In most cases it makes no difference what happens to the original block
790 when @code{realloc} fails, because the application program cannot continue
791 when it is out of memory, and the only thing to do is to give a fatal error
792 message.  Often it is convenient to write and use a subroutine,
793 conventionally called @code{xrealloc}, that takes care of the error message
794 as @code{xmalloc} does for @code{malloc}:
796 @smallexample
797 void *
798 xrealloc (void *ptr, size_t size)
800   void *value = realloc (ptr, size);
801   if (value == 0)
802     fatal ("Virtual memory exhausted");
803   return value;
805 @end smallexample
807 You can also use @code{realloc} to make a block smaller.  The reason you
808 would do this is to avoid tying up a lot of memory space when only a little
809 is needed.
810 @comment The following is no longer true with the new malloc.
811 @comment But it seems wise to keep the warning for other implementations.
812 In several allocation implementations, making a block smaller sometimes
813 necessitates copying it, so it can fail if no other space is available.
815 If the new size you specify is the same as the old size, @code{realloc}
816 is guaranteed to change nothing and return the same address that you gave.
818 @node Allocating Cleared Space
819 @subsubsection Allocating Cleared Space
821 The function @code{calloc} allocates memory and clears it to zero.  It
822 is declared in @file{stdlib.h}.
823 @pindex stdlib.h
825 @comment malloc.h stdlib.h
826 @comment ISO
827 @deftypefun {void *} calloc (size_t @var{count}, size_t @var{eltsize})
828 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
829 @c Same caveats as malloc.
831 @c __libc_calloc @asulock @aculock @acsfd @acsmem
832 @c  *__malloc_hook dup unguarded
833 @c  memset dup ok
834 @c  arena_get @asulock @aculock @acsfd @acsmem
835 @c   arena_lock dup @asulock @aculock @acsfd @acsmem
836 @c  top dup ok
837 @c  chunksize dup ok
838 @c  heap_for_ptr dup ok
839 @c  _int_malloc dup @acsfd @acsmem
840 @c  arena_get_retry dup @asulock @aculock @acsfd @acsmem
841 @c  mutex_unlock dup @aculock
842 @c  mem2chunk dup ok
843 @c  chunk_is_mmapped dup ok
844 @c  MALLOC_ZERO ok
845 @c   memset dup ok
846 This function allocates a block long enough to contain a vector of
847 @var{count} elements, each of size @var{eltsize}.  Its contents are
848 cleared to zero before @code{calloc} returns.
849 @end deftypefun
851 You could define @code{calloc} as follows:
853 @smallexample
854 void *
855 calloc (size_t count, size_t eltsize)
857   size_t size = count * eltsize;
858   void *value = malloc (size);
859   if (value != 0)
860     memset (value, 0, size);
861   return value;
863 @end smallexample
865 But in general, it is not guaranteed that @code{calloc} calls
866 @code{malloc} internally.  Therefore, if an application provides its own
867 @code{malloc}/@code{realloc}/@code{free} outside the C library, it
868 should always define @code{calloc}, too.
870 @node Efficiency and Malloc
871 @subsubsection Efficiency Considerations for @code{malloc}
872 @cindex efficiency and @code{malloc}
877 @ignore
879 @c No longer true, see below instead.
880 To make the best use of @code{malloc}, it helps to know that the GNU
881 version of @code{malloc} always dispenses small amounts of memory in
882 blocks whose sizes are powers of two.  It keeps separate pools for each
883 power of two.  This holds for sizes up to a page size.  Therefore, if
884 you are free to choose the size of a small block in order to make
885 @code{malloc} more efficient, make it a power of two.
886 @c !!! xref getpagesize
888 Once a page is split up for a particular block size, it can't be reused
889 for another size unless all the blocks in it are freed.  In many
890 programs, this is unlikely to happen.  Thus, you can sometimes make a
891 program use memory more efficiently by using blocks of the same size for
892 many different purposes.
894 When you ask for memory blocks of a page or larger, @code{malloc} uses a
895 different strategy; it rounds the size up to a multiple of a page, and
896 it can coalesce and split blocks as needed.
898 The reason for the two strategies is that it is important to allocate
899 and free small blocks as fast as possible, but speed is less important
900 for a large block since the program normally spends a fair amount of
901 time using it.  Also, large blocks are normally fewer in number.
902 Therefore, for large blocks, it makes sense to use a method which takes
903 more time to minimize the wasted space.
905 @end ignore
907 As opposed to other versions, the @code{malloc} in @theglibc{}
908 does not round up block sizes to powers of two, neither for large nor
909 for small sizes.  Neighboring chunks can be coalesced on a @code{free}
910 no matter what their size is.  This makes the implementation suitable
911 for all kinds of allocation patterns without generally incurring high
912 memory waste through fragmentation.
914 Very large blocks (much larger than a page) are allocated with
915 @code{mmap} (anonymous or via @code{/dev/zero}) by this implementation.
916 This has the great advantage that these chunks are returned to the
917 system immediately when they are freed.  Therefore, it cannot happen
918 that a large chunk becomes ``locked'' in between smaller ones and even
919 after calling @code{free} wastes memory.  The size threshold for
920 @code{mmap} to be used can be adjusted with @code{mallopt}.  The use of
921 @code{mmap} can also be disabled completely.
923 @node Aligned Memory Blocks
924 @subsubsection Allocating Aligned Memory Blocks
926 @cindex page boundary
927 @cindex alignment (with @code{malloc})
928 @pindex stdlib.h
929 The address of a block returned by @code{malloc} or @code{realloc} in
930 @gnusystems{} is always a multiple of eight (or sixteen on 64-bit
931 systems).  If you need a block whose address is a multiple of a higher
932 power of two than that, use @code{aligned_alloc} or @code{posix_memalign}.
933 @code{aligned_alloc} and @code{posix_memalign} are declared in
934 @file{stdlib.h}.
936 @comment stdlib.h
937 @deftypefun {void *} aligned_alloc (size_t @var{alignment}, size_t @var{size})
938 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
939 @c Alias to memalign.
940 The @code{aligned_alloc} function allocates a block of @var{size} bytes whose
941 address is a multiple of @var{alignment}.  The @var{alignment} must be a
942 power of two and @var{size} must be a multiple of @var{alignment}.
944 The @code{aligned_alloc} function returns a null pointer on error and sets
945 @code{errno} to one of the following values:
947 @table @code
948 @item ENOMEM
949 There was insufficient memory available to satisfy the request.
951 @item EINVAL
952 @var{alignment} is not a power of two.
954 This function was introduced in @w{ISO C11} and hence may have better
955 portability to modern non-POSIX systems than @code{posix_memalign}.
956 @end table
958 @end deftypefun
960 @comment malloc.h
961 @comment BSD
962 @deftypefun {void *} memalign (size_t @var{boundary}, size_t @var{size})
963 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
964 @c Same issues as malloc.  The padding bytes are safely freed in
965 @c _int_memalign, with the arena still locked.
967 @c __libc_memalign @asulock @aculock @acsfd @acsmem
968 @c  *__memalign_hook dup unguarded
969 @c  __libc_malloc dup @asulock @aculock @acsfd @acsmem
970 @c  arena_get dup @asulock @aculock @acsfd @acsmem
971 @c  _int_memalign @acsfd @acsmem
972 @c   _int_malloc dup @acsfd @acsmem
973 @c   checked_request2size dup ok
974 @c   mem2chunk dup ok
975 @c   chunksize dup ok
976 @c   chunk_is_mmapped dup ok
977 @c   set_head dup ok
978 @c   chunk2mem dup ok
979 @c   set_inuse_bit_at_offset dup ok
980 @c   set_head_size dup ok
981 @c   _int_free (have_lock) dup @acsfd @acsmem
982 @c   chunk_at_offset dup ok
983 @c   check_inuse_chunk dup ok
984 @c  arena_get_retry dup @asulock @aculock @acsfd @acsmem
985 @c  mutex_unlock dup @aculock
986 The @code{memalign} function allocates a block of @var{size} bytes whose
987 address is a multiple of @var{boundary}.  The @var{boundary} must be a
988 power of two!  The function @code{memalign} works by allocating a
989 somewhat larger block, and then returning an address within the block
990 that is on the specified boundary.
992 The @code{memalign} function returns a null pointer on error and sets
993 @code{errno} to one of the following values:
995 @table @code
996 @item ENOMEM
997 There was insufficient memory available to satisfy the request.
999 @item EINVAL
1000 @var{boundary} is not a power of two.
1002 @end table
1004 The @code{memalign} function is obsolete and @code{aligned_alloc} or
1005 @code{posix_memalign} should be used instead.
1006 @end deftypefun
1008 @comment stdlib.h
1009 @comment POSIX
1010 @deftypefun int posix_memalign (void **@var{memptr}, size_t @var{alignment}, size_t @var{size})
1011 @safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
1012 @c Calls memalign unless the requirements are not met (powerof2 macro is
1013 @c safe given an automatic variable as an argument) or there's a
1014 @c memalign hook (accessed unguarded, but safely).
1015 The @code{posix_memalign} function is similar to the @code{memalign}
1016 function in that it returns a buffer of @var{size} bytes aligned to a
1017 multiple of @var{alignment}.  But it adds one requirement to the
1018 parameter @var{alignment}: the value must be a power of two multiple of
1019 @code{sizeof (void *)}.
1021 If the function succeeds in allocation memory a pointer to the allocated
1022 memory is returned in @code{*@var{memptr}} and the return value is zero.
1023 Otherwise the function returns an error value indicating the problem.
1024 The possible error values returned are:
1026 @table @code
1027 @item ENOMEM
1028 There was insufficient memory available to satisfy the request.
1030 @item EINVAL
1031 @var{alignment} is not a power of two multiple of @code{sizeof (void *)}.
1033 @end table
1035 This function was introduced in POSIX 1003.1d.  Although this function is
1036 superseded by @code{aligned_alloc}, it is more portable to older POSIX
1037 systems that do not support @w{ISO C11}.
1038 @end deftypefun
1040 @comment malloc.h stdlib.h
1041 @comment BSD
1042 @deftypefun {void *} valloc (size_t @var{size})
1043 @safety{@prelim{}@mtunsafe{@mtuinit{}}@asunsafe{@asuinit{} @asulock{}}@acunsafe{@acuinit{} @aculock{} @acsfd{} @acsmem{}}}
1044 @c __libc_valloc @mtuinit @asuinit @asulock @aculock @acsfd @acsmem
1045 @c  ptmalloc_init (once) @mtsenv @asulock @aculock @acsfd @acsmem
1046 @c   _dl_addr @asucorrupt? @aculock
1047 @c    __rtld_lock_lock_recursive (dl_load_lock) @asucorrupt? @aculock
1048 @c    _dl_find_dso_for_object ok, iterates over dl_ns and its _ns_loaded objs
1049 @c      the ok above assumes no partial updates on dl_ns and _ns_loaded
1050 @c      that could confuse a _dl_addr call in a signal handler
1051 @c     _dl_addr_inside_object ok
1052 @c    determine_info ok
1053 @c    __rtld_lock_unlock_recursive (dl_load_lock) @aculock
1054 @c   *_environ @mtsenv
1055 @c   next_env_entry ok
1056 @c   strcspn dup ok
1057 @c   __libc_mallopt dup @mtasuconst:mallopt [setting mp_]
1058 @c   __malloc_check_init @mtasuconst:malloc_hooks [setting hooks]
1059 @c   *__malloc_initialize_hook unguarded, ok
1060 @c  *__memalign_hook dup ok, unguarded
1061 @c  arena_get dup @asulock @aculock @acsfd @acsmem
1062 @c  _int_valloc @acsfd @acsmem
1063 @c   malloc_consolidate dup ok
1064 @c   _int_memalign dup @acsfd @acsmem
1065 @c  arena_get_retry dup @asulock @aculock @acsfd @acsmem
1066 @c  _int_memalign dup @acsfd @acsmem
1067 @c  mutex_unlock dup @aculock
1068 Using @code{valloc} is like using @code{memalign} and passing the page size
1069 as the value of the first argument.  It is implemented like this:
1071 @smallexample
1072 void *
1073 valloc (size_t size)
1075   return memalign (getpagesize (), size);
1077 @end smallexample
1079 @ref{Query Memory Parameters} for more information about the memory
1080 subsystem.
1082 The @code{valloc} function is obsolete and @code{aligned_alloc} or
1083 @code{posix_memalign} should be used instead.
1084 @end deftypefun
1086 @node Malloc Tunable Parameters
1087 @subsubsection Malloc Tunable Parameters
1089 You can adjust some parameters for dynamic memory allocation with the
1090 @code{mallopt} function.  This function is the general SVID/XPG
1091 interface, defined in @file{malloc.h}.
1092 @pindex malloc.h
1094 @deftypefun int mallopt (int @var{param}, int @var{value})
1095 @safety{@prelim{}@mtunsafe{@mtuinit{} @mtasuconst{:mallopt}}@asunsafe{@asuinit{} @asulock{}}@acunsafe{@acuinit{} @aculock{}}}
1096 @c __libc_mallopt @mtuinit @mtasuconst:mallopt @asuinit @asulock @aculock
1097 @c  ptmalloc_init (once) dup @mtsenv @asulock @aculock @acsfd @acsmem
1098 @c  mutex_lock (main_arena->mutex) @asulock @aculock
1099 @c  malloc_consolidate dup ok
1100 @c  set_max_fast ok
1101 @c  mutex_unlock dup @aculock
1103 When calling @code{mallopt}, the @var{param} argument specifies the
1104 parameter to be set, and @var{value} the new value to be set.  Possible
1105 choices for @var{param}, as defined in @file{malloc.h}, are:
1107 @table @code
1108 @comment TODO: @item M_ARENA_MAX
1109 @comment       - Document ARENA_MAX env var.
1110 @comment TODO: @item M_ARENA_TEST
1111 @comment       - Document ARENA_TEST env var.
1112 @comment TODO: @item M_CHECK_ACTION
1113 @item M_MMAP_MAX
1114 The maximum number of chunks to allocate with @code{mmap}.  Setting this
1115 to zero disables all use of @code{mmap}.
1116 @item M_MMAP_THRESHOLD
1117 All chunks larger than this value are allocated outside the normal
1118 heap, using the @code{mmap} system call.  This way it is guaranteed
1119 that the memory for these chunks can be returned to the system on
1120 @code{free}.  Note that requests smaller than this threshold might still
1121 be allocated via @code{mmap}.
1122 @comment TODO: @item M_MXFAST
1123 @item M_PERTURB
1124 If non-zero, memory blocks are filled with values depending on some
1125 low order bits of this parameter when they are allocated (except when
1126 allocated by @code{calloc}) and freed.  This can be used to debug the
1127 use of uninitialized or freed heap memory.  Note that this option does not
1128 guarantee that the freed block will have any specific values.  It only
1129 guarantees that the content the block had before it was freed will be
1130 overwritten.
1131 @item M_TOP_PAD
1132 This parameter determines the amount of extra memory to obtain from the
1133 system when a call to @code{sbrk} is required.  It also specifies the
1134 number of bytes to retain when shrinking the heap by calling @code{sbrk}
1135 with a negative argument.  This provides the necessary hysteresis in
1136 heap size such that excessive amounts of system calls can be avoided.
1137 @item M_TRIM_THRESHOLD
1138 This is the minimum size (in bytes) of the top-most, releasable chunk
1139 that will cause @code{sbrk} to be called with a negative argument in
1140 order to return memory to the system.
1141 @end table
1143 @end deftypefun
1145 @node Heap Consistency Checking
1146 @subsubsection Heap Consistency Checking
1148 @cindex heap consistency checking
1149 @cindex consistency checking, of heap
1151 You can ask @code{malloc} to check the consistency of dynamic memory by
1152 using the @code{mcheck} function.  This function is a GNU extension,
1153 declared in @file{mcheck.h}.
1154 @pindex mcheck.h
1156 @comment mcheck.h
1157 @comment GNU
1158 @deftypefun int mcheck (void (*@var{abortfn}) (enum mcheck_status @var{status}))
1159 @safety{@prelim{}@mtunsafe{@mtasurace{:mcheck} @mtasuconst{:malloc_hooks}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
1160 @c The hooks must be set up before malloc is first used, which sort of
1161 @c implies @mtuinit/@asuinit but since the function is a no-op if malloc
1162 @c was already used, that doesn't pose any safety issues.  The actual
1163 @c problem is with the hooks, designed for single-threaded
1164 @c fully-synchronous operation: they manage an unguarded linked list of
1165 @c allocated blocks, and get temporarily overwritten before calling the
1166 @c allocation functions recursively while holding the old hooks.  There
1167 @c are no guards for thread safety, and inconsistent hooks may be found
1168 @c within signal handlers or left behind in case of cancellation.
1170 Calling @code{mcheck} tells @code{malloc} to perform occasional
1171 consistency checks.  These will catch things such as writing
1172 past the end of a block that was allocated with @code{malloc}.
1174 The @var{abortfn} argument is the function to call when an inconsistency
1175 is found.  If you supply a null pointer, then @code{mcheck} uses a
1176 default function which prints a message and calls @code{abort}
1177 (@pxref{Aborting a Program}).  The function you supply is called with
1178 one argument, which says what sort of inconsistency was detected; its
1179 type is described below.
1181 It is too late to begin allocation checking once you have allocated
1182 anything with @code{malloc}.  So @code{mcheck} does nothing in that
1183 case.  The function returns @code{-1} if you call it too late, and
1184 @code{0} otherwise (when it is successful).
1186 The easiest way to arrange to call @code{mcheck} early enough is to use
1187 the option @samp{-lmcheck} when you link your program; then you don't
1188 need to modify your program source at all.  Alternatively you might use
1189 a debugger to insert a call to @code{mcheck} whenever the program is
1190 started, for example these gdb commands will automatically call @code{mcheck}
1191 whenever the program starts:
1193 @smallexample
1194 (gdb) break main
1195 Breakpoint 1, main (argc=2, argv=0xbffff964) at whatever.c:10
1196 (gdb) command 1
1197 Type commands for when breakpoint 1 is hit, one per line.
1198 End with a line saying just "end".
1199 >call mcheck(0)
1200 >continue
1201 >end
1202 (gdb) @dots{}
1203 @end smallexample
1205 This will however only work if no initialization function of any object
1206 involved calls any of the @code{malloc} functions since @code{mcheck}
1207 must be called before the first such function.
1209 @end deftypefun
1211 @deftypefun {enum mcheck_status} mprobe (void *@var{pointer})
1212 @safety{@prelim{}@mtunsafe{@mtasurace{:mcheck} @mtasuconst{:malloc_hooks}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
1213 @c The linked list of headers may be modified concurrently by other
1214 @c threads, and it may find a partial update if called from a signal
1215 @c handler.  It's mostly read only, so cancelling it might be safe, but
1216 @c it will modify global state that, if cancellation hits at just the
1217 @c right spot, may be left behind inconsistent.  This path is only taken
1218 @c if checkhdr finds an inconsistency.  If the inconsistency could only
1219 @c occur because of earlier undefined behavior, that wouldn't be an
1220 @c additional safety issue problem, but because of the other concurrency
1221 @c issues in the mcheck hooks, the apparent inconsistency could be the
1222 @c result of mcheck's own internal data race.  So, AC-Unsafe it is.
1224 The @code{mprobe} function lets you explicitly check for inconsistencies
1225 in a particular allocated block.  You must have already called
1226 @code{mcheck} at the beginning of the program, to do its occasional
1227 checks; calling @code{mprobe} requests an additional consistency check
1228 to be done at the time of the call.
1230 The argument @var{pointer} must be a pointer returned by @code{malloc}
1231 or @code{realloc}.  @code{mprobe} returns a value that says what
1232 inconsistency, if any, was found.  The values are described below.
1233 @end deftypefun
1235 @deftp {Data Type} {enum mcheck_status}
1236 This enumerated type describes what kind of inconsistency was detected
1237 in an allocated block, if any.  Here are the possible values:
1239 @table @code
1240 @item MCHECK_DISABLED
1241 @code{mcheck} was not called before the first allocation.
1242 No consistency checking can be done.
1243 @item MCHECK_OK
1244 No inconsistency detected.
1245 @item MCHECK_HEAD
1246 The data immediately before the block was modified.
1247 This commonly happens when an array index or pointer
1248 is decremented too far.
1249 @item MCHECK_TAIL
1250 The data immediately after the block was modified.
1251 This commonly happens when an array index or pointer
1252 is incremented too far.
1253 @item MCHECK_FREE
1254 The block was already freed.
1255 @end table
1256 @end deftp
1258 Another possibility to check for and guard against bugs in the use of
1259 @code{malloc}, @code{realloc} and @code{free} is to set the environment
1260 variable @code{MALLOC_CHECK_}.  When @code{MALLOC_CHECK_} is set, a
1261 special (less efficient) implementation is used which is designed to be
1262 tolerant against simple errors, such as double calls of @code{free} with
1263 the same argument, or overruns of a single byte (off-by-one bugs).  Not
1264 all such errors can be protected against, however, and memory leaks can
1265 result.  If @code{MALLOC_CHECK_} is set to @code{0}, any detected heap
1266 corruption is silently ignored; if set to @code{1}, a diagnostic is
1267 printed on @code{stderr}; if set to @code{2}, @code{abort} is called
1268 immediately.  This can be useful because otherwise a crash may happen
1269 much later, and the true cause for the problem is then very hard to
1270 track down.
1272 There is one problem with @code{MALLOC_CHECK_}: in SUID or SGID binaries
1273 it could possibly be exploited since diverging from the normal programs
1274 behavior it now writes something to the standard error descriptor.
1275 Therefore the use of @code{MALLOC_CHECK_} is disabled by default for
1276 SUID and SGID binaries.  It can be enabled again by the system
1277 administrator by adding a file @file{/etc/suid-debug} (the content is
1278 not important it could be empty).
1280 So, what's the difference between using @code{MALLOC_CHECK_} and linking
1281 with @samp{-lmcheck}?  @code{MALLOC_CHECK_} is orthogonal with respect to
1282 @samp{-lmcheck}.  @samp{-lmcheck} has been added for backward
1283 compatibility.  Both @code{MALLOC_CHECK_} and @samp{-lmcheck} should
1284 uncover the same bugs - but using @code{MALLOC_CHECK_} you don't need to
1285 recompile your application.
1287 @node Hooks for Malloc
1288 @subsubsection Memory Allocation Hooks
1289 @cindex allocation hooks, for @code{malloc}
1291 @Theglibc{} lets you modify the behavior of @code{malloc},
1292 @code{realloc}, and @code{free} by specifying appropriate hook
1293 functions.  You can use these hooks to help you debug programs that use
1294 dynamic memory allocation, for example.
1296 The hook variables are declared in @file{malloc.h}.
1297 @pindex malloc.h
1299 @comment malloc.h
1300 @comment GNU
1301 @defvar __malloc_hook
1302 The value of this variable is a pointer to the function that
1303 @code{malloc} uses whenever it is called.  You should define this
1304 function to look like @code{malloc}; that is, like:
1306 @smallexample
1307 void *@var{function} (size_t @var{size}, const void *@var{caller})
1308 @end smallexample
1310 The value of @var{caller} is the return address found on the stack when
1311 the @code{malloc} function was called.  This value allows you to trace
1312 the memory consumption of the program.
1313 @end defvar
1315 @comment malloc.h
1316 @comment GNU
1317 @defvar __realloc_hook
1318 The value of this variable is a pointer to function that @code{realloc}
1319 uses whenever it is called.  You should define this function to look
1320 like @code{realloc}; that is, like:
1322 @smallexample
1323 void *@var{function} (void *@var{ptr}, size_t @var{size}, const void *@var{caller})
1324 @end smallexample
1326 The value of @var{caller} is the return address found on the stack when
1327 the @code{realloc} function was called.  This value allows you to trace the
1328 memory consumption of the program.
1329 @end defvar
1331 @comment malloc.h
1332 @comment GNU
1333 @defvar __free_hook
1334 The value of this variable is a pointer to function that @code{free}
1335 uses whenever it is called.  You should define this function to look
1336 like @code{free}; that is, like:
1338 @smallexample
1339 void @var{function} (void *@var{ptr}, const void *@var{caller})
1340 @end smallexample
1342 The value of @var{caller} is the return address found on the stack when
1343 the @code{free} function was called.  This value allows you to trace the
1344 memory consumption of the program.
1345 @end defvar
1347 @comment malloc.h
1348 @comment GNU
1349 @defvar __memalign_hook
1350 The value of this variable is a pointer to function that @code{aligned_alloc},
1351 @code{memalign}, @code{posix_memalign} and @code{valloc} use whenever they
1352 are called.  You should define this function to look like @code{aligned_alloc};
1353 that is, like:
1355 @smallexample
1356 void *@var{function} (size_t @var{alignment}, size_t @var{size}, const void *@var{caller})
1357 @end smallexample
1359 The value of @var{caller} is the return address found on the stack when
1360 the @code{aligned_alloc}, @code{memalign}, @code{posix_memalign} or
1361 @code{valloc} functions are called.  This value allows you to trace the
1362 memory consumption of the program.
1363 @end defvar
1365 You must make sure that the function you install as a hook for one of
1366 these functions does not call that function recursively without restoring
1367 the old value of the hook first!  Otherwise, your program will get stuck
1368 in an infinite recursion.  Before calling the function recursively, one
1369 should make sure to restore all the hooks to their previous value.  When
1370 coming back from the recursive call, all the hooks should be resaved
1371 since a hook might modify itself.
1373 An issue to look out for is the time at which the malloc hook functions
1374 can be safely installed.  If the hook functions call the malloc-related
1375 functions recursively, it is necessary that malloc has already properly
1376 initialized itself at the time when @code{__malloc_hook} etc. is
1377 assigned to.  On the other hand, if the hook functions provide a
1378 complete malloc implementation of their own, it is vital that the hooks
1379 are assigned to @emph{before} the very first @code{malloc} call has
1380 completed, because otherwise a chunk obtained from the ordinary,
1381 un-hooked malloc may later be handed to @code{__free_hook}, for example.
1383 Here is an example showing how to use @code{__malloc_hook} and
1384 @code{__free_hook} properly.  It installs a function that prints out
1385 information every time @code{malloc} or @code{free} is called.  We just
1386 assume here that @code{realloc} and @code{memalign} are not used in our
1387 program.
1389 @smallexample
1390 /* Prototypes for __malloc_hook, __free_hook */
1391 #include <malloc.h>
1393 /* Prototypes for our hooks.  */
1394 static void my_init_hook (void);
1395 static void *my_malloc_hook (size_t, const void *);
1396 static void my_free_hook (void*, const void *);
1398 static void
1399 my_init (void)
1401   old_malloc_hook = __malloc_hook;
1402   old_free_hook = __free_hook;
1403   __malloc_hook = my_malloc_hook;
1404   __free_hook = my_free_hook;
1407 static void *
1408 my_malloc_hook (size_t size, const void *caller)
1410   void *result;
1411   /* Restore all old hooks */
1412   __malloc_hook = old_malloc_hook;
1413   __free_hook = old_free_hook;
1414   /* Call recursively */
1415   result = malloc (size);
1416   /* Save underlying hooks */
1417   old_malloc_hook = __malloc_hook;
1418   old_free_hook = __free_hook;
1419   /* @r{@code{printf} might call @code{malloc}, so protect it too.} */
1420   printf ("malloc (%u) returns %p\n", (unsigned int) size, result);
1421   /* Restore our own hooks */
1422   __malloc_hook = my_malloc_hook;
1423   __free_hook = my_free_hook;
1424   return result;
1427 static void
1428 my_free_hook (void *ptr, const void *caller)
1430   /* Restore all old hooks */
1431   __malloc_hook = old_malloc_hook;
1432   __free_hook = old_free_hook;
1433   /* Call recursively */
1434   free (ptr);
1435   /* Save underlying hooks */
1436   old_malloc_hook = __malloc_hook;
1437   old_free_hook = __free_hook;
1438   /* @r{@code{printf} might call @code{free}, so protect it too.} */
1439   printf ("freed pointer %p\n", ptr);
1440   /* Restore our own hooks */
1441   __malloc_hook = my_malloc_hook;
1442   __free_hook = my_free_hook;
1445 main ()
1447   my_init ();
1448   @dots{}
1450 @end smallexample
1452 The @code{mcheck} function (@pxref{Heap Consistency Checking}) works by
1453 installing such hooks.
1455 @c __morecore, __after_morecore_hook are undocumented
1456 @c It's not clear whether to document them.
1458 @node Statistics of Malloc
1459 @subsubsection Statistics for Memory Allocation with @code{malloc}
1461 @cindex allocation statistics
1462 You can get information about dynamic memory allocation by calling the
1463 @code{mallinfo} function.  This function and its associated data type
1464 are declared in @file{malloc.h}; they are an extension of the standard
1465 SVID/XPG version.
1466 @pindex malloc.h
1468 @comment malloc.h
1469 @comment GNU
1470 @deftp {Data Type} {struct mallinfo}
1471 This structure type is used to return information about the dynamic
1472 memory allocator.  It contains the following members:
1474 @table @code
1475 @item int arena
1476 This is the total size of memory allocated with @code{sbrk} by
1477 @code{malloc}, in bytes.
1479 @item int ordblks
1480 This is the number of chunks not in use.  (The memory allocator
1481 internally gets chunks of memory from the operating system, and then
1482 carves them up to satisfy individual @code{malloc} requests; see
1483 @ref{Efficiency and Malloc}.)
1485 @item int smblks
1486 This field is unused.
1488 @item int hblks
1489 This is the total number of chunks allocated with @code{mmap}.
1491 @item int hblkhd
1492 This is the total size of memory allocated with @code{mmap}, in bytes.
1494 @item int usmblks
1495 This field is unused and always 0.
1497 @item int fsmblks
1498 This field is unused.
1500 @item int uordblks
1501 This is the total size of memory occupied by chunks handed out by
1502 @code{malloc}.
1504 @item int fordblks
1505 This is the total size of memory occupied by free (not in use) chunks.
1507 @item int keepcost
1508 This is the size of the top-most releasable chunk that normally
1509 borders the end of the heap (i.e., the high end of the virtual address
1510 space's data segment).
1512 @end table
1513 @end deftp
1515 @comment malloc.h
1516 @comment SVID
1517 @deftypefun {struct mallinfo} mallinfo (void)
1518 @safety{@prelim{}@mtunsafe{@mtuinit{} @mtasuconst{:mallopt}}@asunsafe{@asuinit{} @asulock{}}@acunsafe{@acuinit{} @aculock{}}}
1519 @c Accessing mp_.n_mmaps and mp_.max_mmapped_mem, modified with atomics
1520 @c but non-atomically elsewhere, may get us inconsistent results.  We
1521 @c mark the statistics as unsafe, rather than the fast-path functions
1522 @c that collect the possibly inconsistent data.
1524 @c __libc_mallinfo @mtuinit @mtasuconst:mallopt @asuinit @asulock @aculock
1525 @c  ptmalloc_init (once) dup @mtsenv @asulock @aculock @acsfd @acsmem
1526 @c  mutex_lock dup @asulock @aculock
1527 @c  int_mallinfo @mtasuconst:mallopt [mp_ access on main_arena]
1528 @c   malloc_consolidate dup ok
1529 @c   check_malloc_state dup ok/disabled
1530 @c   chunksize dup ok
1531 @c   fastbin dupo ok
1532 @c   bin_at dup ok
1533 @c   last dup ok
1534 @c  mutex_unlock @aculock
1536 This function returns information about the current dynamic memory usage
1537 in a structure of type @code{struct mallinfo}.
1538 @end deftypefun
1540 @node Summary of Malloc
1541 @subsubsection Summary of @code{malloc}-Related Functions
1543 Here is a summary of the functions that work with @code{malloc}:
1545 @table @code
1546 @item void *malloc (size_t @var{size})
1547 Allocate a block of @var{size} bytes.  @xref{Basic Allocation}.
1549 @item void free (void *@var{addr})
1550 Free a block previously allocated by @code{malloc}.  @xref{Freeing after
1551 Malloc}.
1553 @item void *realloc (void *@var{addr}, size_t @var{size})
1554 Make a block previously allocated by @code{malloc} larger or smaller,
1555 possibly by copying it to a new location.  @xref{Changing Block Size}.
1557 @item void *calloc (size_t @var{count}, size_t @var{eltsize})
1558 Allocate a block of @var{count} * @var{eltsize} bytes using
1559 @code{malloc}, and set its contents to zero.  @xref{Allocating Cleared
1560 Space}.
1562 @item void *valloc (size_t @var{size})
1563 Allocate a block of @var{size} bytes, starting on a page boundary.
1564 @xref{Aligned Memory Blocks}.
1566 @item void *aligned_alloc (size_t @var{size}, size_t @var{alignment})
1567 Allocate a block of @var{size} bytes, starting on an address that is a
1568 multiple of @var{alignment}.  @xref{Aligned Memory Blocks}.
1570 @item int posix_memalign (void **@var{memptr}, size_t @var{alignment}, size_t @var{size})
1571 Allocate a block of @var{size} bytes, starting on an address that is a
1572 multiple of @var{alignment}.  @xref{Aligned Memory Blocks}.
1574 @item void *memalign (size_t @var{size}, size_t @var{boundary})
1575 Allocate a block of @var{size} bytes, starting on an address that is a
1576 multiple of @var{boundary}.  @xref{Aligned Memory Blocks}.
1578 @item int mallopt (int @var{param}, int @var{value})
1579 Adjust a tunable parameter.  @xref{Malloc Tunable Parameters}.
1581 @item int mcheck (void (*@var{abortfn}) (void))
1582 Tell @code{malloc} to perform occasional consistency checks on
1583 dynamically allocated memory, and to call @var{abortfn} when an
1584 inconsistency is found.  @xref{Heap Consistency Checking}.
1586 @item void *(*__malloc_hook) (size_t @var{size}, const void *@var{caller})
1587 A pointer to a function that @code{malloc} uses whenever it is called.
1589 @item void *(*__realloc_hook) (void *@var{ptr}, size_t @var{size}, const void *@var{caller})
1590 A pointer to a function that @code{realloc} uses whenever it is called.
1592 @item void (*__free_hook) (void *@var{ptr}, const void *@var{caller})
1593 A pointer to a function that @code{free} uses whenever it is called.
1595 @item void (*__memalign_hook) (size_t @var{size}, size_t @var{alignment}, const void *@var{caller})
1596 A pointer to a function that @code{aligned_alloc}, @code{memalign},
1597 @code{posix_memalign} and @code{valloc} use whenever they are called.
1599 @item struct mallinfo mallinfo (void)
1600 Return information about the current dynamic memory usage.
1601 @xref{Statistics of Malloc}.
1602 @end table
1604 @node Allocation Debugging
1605 @subsection Allocation Debugging
1606 @cindex allocation debugging
1607 @cindex malloc debugger
1609 A complicated task when programming with languages which do not use
1610 garbage collected dynamic memory allocation is to find memory leaks.
1611 Long running programs must ensure that dynamically allocated objects are
1612 freed at the end of their lifetime.  If this does not happen the system
1613 runs out of memory, sooner or later.
1615 The @code{malloc} implementation in @theglibc{} provides some
1616 simple means to detect such leaks and obtain some information to find
1617 the location.  To do this the application must be started in a special
1618 mode which is enabled by an environment variable.  There are no speed
1619 penalties for the program if the debugging mode is not enabled.
1621 @menu
1622 * Tracing malloc::               How to install the tracing functionality.
1623 * Using the Memory Debugger::    Example programs excerpts.
1624 * Tips for the Memory Debugger:: Some more or less clever ideas.
1625 * Interpreting the traces::      What do all these lines mean?
1626 @end menu
1628 @node Tracing malloc
1629 @subsubsection How to install the tracing functionality
1631 @comment mcheck.h
1632 @comment GNU
1633 @deftypefun void mtrace (void)
1634 @safety{@prelim{}@mtunsafe{@mtsenv{} @mtasurace{:mtrace} @mtasuconst{:malloc_hooks} @mtuinit{}}@asunsafe{@asuinit{} @ascuheap{} @asucorrupt{} @asulock{}}@acunsafe{@acuinit{} @acucorrupt{} @aculock{} @acsfd{} @acsmem{}}}
1635 @c Like the mcheck hooks, these are not designed with thread safety in
1636 @c mind, because the hook pointers are temporarily modified without
1637 @c regard to other threads, signals or cancellation.
1639 @c mtrace @mtuinit @mtasurace:mtrace @mtsenv @asuinit @ascuheap @asucorrupt @acuinit @acucorrupt @aculock @acsfd @acsmem
1640 @c  __libc_secure_getenv dup @mtsenv
1641 @c  malloc dup @ascuheap @acsmem
1642 @c  fopen dup @ascuheap @asulock @aculock @acsmem @acsfd
1643 @c  fcntl dup ok
1644 @c  setvbuf dup @aculock
1645 @c  fprintf dup (on newly-created stream) @aculock
1646 @c  __cxa_atexit (once) dup @asulock @aculock @acsmem
1647 @c  free dup @ascuheap @acsmem
1648 When the @code{mtrace} function is called it looks for an environment
1649 variable named @code{MALLOC_TRACE}.  This variable is supposed to
1650 contain a valid file name.  The user must have write access.  If the
1651 file already exists it is truncated.  If the environment variable is not
1652 set or it does not name a valid file which can be opened for writing
1653 nothing is done.  The behavior of @code{malloc} etc. is not changed.
1654 For obvious reasons this also happens if the application is installed
1655 with the SUID or SGID bit set.
1657 If the named file is successfully opened, @code{mtrace} installs special
1658 handlers for the functions @code{malloc}, @code{realloc}, and
1659 @code{free} (@pxref{Hooks for Malloc}).  From then on, all uses of these
1660 functions are traced and protocolled into the file.  There is now of
1661 course a speed penalty for all calls to the traced functions so tracing
1662 should not be enabled during normal use.
1664 This function is a GNU extension and generally not available on other
1665 systems.  The prototype can be found in @file{mcheck.h}.
1666 @end deftypefun
1668 @comment mcheck.h
1669 @comment GNU
1670 @deftypefun void muntrace (void)
1671 @safety{@prelim{}@mtunsafe{@mtasurace{:mtrace} @mtasuconst{:malloc_hooks} @mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acucorrupt{} @acsmem{} @aculock{} @acsfd{}}}
1673 @c muntrace @mtasurace:mtrace @mtslocale @asucorrupt @ascuheap @acucorrupt @acsmem @aculock @acsfd
1674 @c  fprintf (fputs) dup @mtslocale @asucorrupt @ascuheap @acsmem @aculock @acucorrupt
1675 @c  fclose dup @ascuheap @asulock @aculock @acsmem @acsfd
1676 The @code{muntrace} function can be called after @code{mtrace} was used
1677 to enable tracing the @code{malloc} calls.  If no (successful) call of
1678 @code{mtrace} was made @code{muntrace} does nothing.
1680 Otherwise it deinstalls the handlers for @code{malloc}, @code{realloc},
1681 and @code{free} and then closes the protocol file.  No calls are
1682 protocolled anymore and the program runs again at full speed.
1684 This function is a GNU extension and generally not available on other
1685 systems.  The prototype can be found in @file{mcheck.h}.
1686 @end deftypefun
1688 @node Using the Memory Debugger
1689 @subsubsection Example program excerpts
1691 Even though the tracing functionality does not influence the runtime
1692 behavior of the program it is not a good idea to call @code{mtrace} in
1693 all programs.  Just imagine that you debug a program using @code{mtrace}
1694 and all other programs used in the debugging session also trace their
1695 @code{malloc} calls.  The output file would be the same for all programs
1696 and thus is unusable.  Therefore one should call @code{mtrace} only if
1697 compiled for debugging.  A program could therefore start like this:
1699 @example
1700 #include <mcheck.h>
1703 main (int argc, char *argv[])
1705 #ifdef DEBUGGING
1706   mtrace ();
1707 #endif
1708   @dots{}
1710 @end example
1712 This is all that is needed if you want to trace the calls during the
1713 whole runtime of the program.  Alternatively you can stop the tracing at
1714 any time with a call to @code{muntrace}.  It is even possible to restart
1715 the tracing again with a new call to @code{mtrace}.  But this can cause
1716 unreliable results since there may be calls of the functions which are
1717 not called.  Please note that not only the application uses the traced
1718 functions, also libraries (including the C library itself) use these
1719 functions.
1721 This last point is also why it is not a good idea to call @code{muntrace}
1722 before the program terminates.  The libraries are informed about the
1723 termination of the program only after the program returns from
1724 @code{main} or calls @code{exit} and so cannot free the memory they use
1725 before this time.
1727 So the best thing one can do is to call @code{mtrace} as the very first
1728 function in the program and never call @code{muntrace}.  So the program
1729 traces almost all uses of the @code{malloc} functions (except those
1730 calls which are executed by constructors of the program or used
1731 libraries).
1733 @node Tips for the Memory Debugger
1734 @subsubsection Some more or less clever ideas
1736 You know the situation.  The program is prepared for debugging and in
1737 all debugging sessions it runs well.  But once it is started without
1738 debugging the error shows up.  A typical example is a memory leak that
1739 becomes visible only when we turn off the debugging.  If you foresee
1740 such situations you can still win.  Simply use something equivalent to
1741 the following little program:
1743 @example
1744 #include <mcheck.h>
1745 #include <signal.h>
1747 static void
1748 enable (int sig)
1750   mtrace ();
1751   signal (SIGUSR1, enable);
1754 static void
1755 disable (int sig)
1757   muntrace ();
1758   signal (SIGUSR2, disable);
1762 main (int argc, char *argv[])
1764   @dots{}
1766   signal (SIGUSR1, enable);
1767   signal (SIGUSR2, disable);
1769   @dots{}
1771 @end example
1773 I.e., the user can start the memory debugger any time s/he wants if the
1774 program was started with @code{MALLOC_TRACE} set in the environment.
1775 The output will of course not show the allocations which happened before
1776 the first signal but if there is a memory leak this will show up
1777 nevertheless.
1779 @node Interpreting the traces
1780 @subsubsection Interpreting the traces
1782 If you take a look at the output it will look similar to this:
1784 @example
1785 = Start
1786 @ [0x8048209] - 0x8064cc8
1787 @ [0x8048209] - 0x8064ce0
1788 @ [0x8048209] - 0x8064cf8
1789 @ [0x80481eb] + 0x8064c48 0x14
1790 @ [0x80481eb] + 0x8064c60 0x14
1791 @ [0x80481eb] + 0x8064c78 0x14
1792 @ [0x80481eb] + 0x8064c90 0x14
1793 = End
1794 @end example
1796 What this all means is not really important since the trace file is not
1797 meant to be read by a human.  Therefore no attention is given to
1798 readability.  Instead there is a program which comes with @theglibc{}
1799 which interprets the traces and outputs a summary in an
1800 user-friendly way.  The program is called @code{mtrace} (it is in fact a
1801 Perl script) and it takes one or two arguments.  In any case the name of
1802 the file with the trace output must be specified.  If an optional
1803 argument precedes the name of the trace file this must be the name of
1804 the program which generated the trace.
1806 @example
1807 drepper$ mtrace tst-mtrace log
1808 No memory leaks.
1809 @end example
1811 In this case the program @code{tst-mtrace} was run and it produced a
1812 trace file @file{log}.  The message printed by @code{mtrace} shows there
1813 are no problems with the code, all allocated memory was freed
1814 afterwards.
1816 If we call @code{mtrace} on the example trace given above we would get a
1817 different outout:
1819 @example
1820 drepper$ mtrace errlog
1821 - 0x08064cc8 Free 2 was never alloc'd 0x8048209
1822 - 0x08064ce0 Free 3 was never alloc'd 0x8048209
1823 - 0x08064cf8 Free 4 was never alloc'd 0x8048209
1825 Memory not freed:
1826 -----------------
1827    Address     Size     Caller
1828 0x08064c48     0x14  at 0x80481eb
1829 0x08064c60     0x14  at 0x80481eb
1830 0x08064c78     0x14  at 0x80481eb
1831 0x08064c90     0x14  at 0x80481eb
1832 @end example
1834 We have called @code{mtrace} with only one argument and so the script
1835 has no chance to find out what is meant with the addresses given in the
1836 trace.  We can do better:
1838 @example
1839 drepper$ mtrace tst errlog
1840 - 0x08064cc8 Free 2 was never alloc'd /home/drepper/tst.c:39
1841 - 0x08064ce0 Free 3 was never alloc'd /home/drepper/tst.c:39
1842 - 0x08064cf8 Free 4 was never alloc'd /home/drepper/tst.c:39
1844 Memory not freed:
1845 -----------------
1846    Address     Size     Caller
1847 0x08064c48     0x14  at /home/drepper/tst.c:33
1848 0x08064c60     0x14  at /home/drepper/tst.c:33
1849 0x08064c78     0x14  at /home/drepper/tst.c:33
1850 0x08064c90     0x14  at /home/drepper/tst.c:33
1851 @end example
1853 Suddenly the output makes much more sense and the user can see
1854 immediately where the function calls causing the trouble can be found.
1856 Interpreting this output is not complicated.  There are at most two
1857 different situations being detected.  First, @code{free} was called for
1858 pointers which were never returned by one of the allocation functions.
1859 This is usually a very bad problem and what this looks like is shown in
1860 the first three lines of the output.  Situations like this are quite
1861 rare and if they appear they show up very drastically: the program
1862 normally crashes.
1864 The other situation which is much harder to detect are memory leaks.  As
1865 you can see in the output the @code{mtrace} function collects all this
1866 information and so can say that the program calls an allocation function
1867 from line 33 in the source file @file{/home/drepper/tst-mtrace.c} four
1868 times without freeing this memory before the program terminates.
1869 Whether this is a real problem remains to be investigated.
1871 @node Obstacks
1872 @subsection Obstacks
1873 @cindex obstacks
1875 An @dfn{obstack} is a pool of memory containing a stack of objects.  You
1876 can create any number of separate obstacks, and then allocate objects in
1877 specified obstacks.  Within each obstack, the last object allocated must
1878 always be the first one freed, but distinct obstacks are independent of
1879 each other.
1881 Aside from this one constraint of order of freeing, obstacks are totally
1882 general: an obstack can contain any number of objects of any size.  They
1883 are implemented with macros, so allocation is usually very fast as long as
1884 the objects are usually small.  And the only space overhead per object is
1885 the padding needed to start each object on a suitable boundary.
1887 @menu
1888 * Creating Obstacks::           How to declare an obstack in your program.
1889 * Preparing for Obstacks::      Preparations needed before you can
1890                                  use obstacks.
1891 * Allocation in an Obstack::    Allocating objects in an obstack.
1892 * Freeing Obstack Objects::     Freeing objects in an obstack.
1893 * Obstack Functions::           The obstack functions are both
1894                                  functions and macros.
1895 * Growing Objects::             Making an object bigger by stages.
1896 * Extra Fast Growing::          Extra-high-efficiency (though more
1897                                  complicated) growing objects.
1898 * Status of an Obstack::        Inquiries about the status of an obstack.
1899 * Obstacks Data Alignment::     Controlling alignment of objects in obstacks.
1900 * Obstack Chunks::              How obstacks obtain and release chunks;
1901                                  efficiency considerations.
1902 * Summary of Obstacks::
1903 @end menu
1905 @node Creating Obstacks
1906 @subsubsection Creating Obstacks
1908 The utilities for manipulating obstacks are declared in the header
1909 file @file{obstack.h}.
1910 @pindex obstack.h
1912 @comment obstack.h
1913 @comment GNU
1914 @deftp {Data Type} {struct obstack}
1915 An obstack is represented by a data structure of type @code{struct
1916 obstack}.  This structure has a small fixed size; it records the status
1917 of the obstack and how to find the space in which objects are allocated.
1918 It does not contain any of the objects themselves.  You should not try
1919 to access the contents of the structure directly; use only the functions
1920 described in this chapter.
1921 @end deftp
1923 You can declare variables of type @code{struct obstack} and use them as
1924 obstacks, or you can allocate obstacks dynamically like any other kind
1925 of object.  Dynamic allocation of obstacks allows your program to have a
1926 variable number of different stacks.  (You can even allocate an
1927 obstack structure in another obstack, but this is rarely useful.)
1929 All the functions that work with obstacks require you to specify which
1930 obstack to use.  You do this with a pointer of type @code{struct obstack
1931 *}.  In the following, we often say ``an obstack'' when strictly
1932 speaking the object at hand is such a pointer.
1934 The objects in the obstack are packed into large blocks called
1935 @dfn{chunks}.  The @code{struct obstack} structure points to a chain of
1936 the chunks currently in use.
1938 The obstack library obtains a new chunk whenever you allocate an object
1939 that won't fit in the previous chunk.  Since the obstack library manages
1940 chunks automatically, you don't need to pay much attention to them, but
1941 you do need to supply a function which the obstack library should use to
1942 get a chunk.  Usually you supply a function which uses @code{malloc}
1943 directly or indirectly.  You must also supply a function to free a chunk.
1944 These matters are described in the following section.
1946 @node Preparing for Obstacks
1947 @subsubsection Preparing for Using Obstacks
1949 Each source file in which you plan to use the obstack functions
1950 must include the header file @file{obstack.h}, like this:
1952 @smallexample
1953 #include <obstack.h>
1954 @end smallexample
1956 @findex obstack_chunk_alloc
1957 @findex obstack_chunk_free
1958 Also, if the source file uses the macro @code{obstack_init}, it must
1959 declare or define two functions or macros that will be called by the
1960 obstack library.  One, @code{obstack_chunk_alloc}, is used to allocate
1961 the chunks of memory into which objects are packed.  The other,
1962 @code{obstack_chunk_free}, is used to return chunks when the objects in
1963 them are freed.  These macros should appear before any use of obstacks
1964 in the source file.
1966 Usually these are defined to use @code{malloc} via the intermediary
1967 @code{xmalloc} (@pxref{Unconstrained Allocation}).  This is done with
1968 the following pair of macro definitions:
1970 @smallexample
1971 #define obstack_chunk_alloc xmalloc
1972 #define obstack_chunk_free free
1973 @end smallexample
1975 @noindent
1976 Though the memory you get using obstacks really comes from @code{malloc},
1977 using obstacks is faster because @code{malloc} is called less often, for
1978 larger blocks of memory.  @xref{Obstack Chunks}, for full details.
1980 At run time, before the program can use a @code{struct obstack} object
1981 as an obstack, it must initialize the obstack by calling
1982 @code{obstack_init}.
1984 @comment obstack.h
1985 @comment GNU
1986 @deftypefun int obstack_init (struct obstack *@var{obstack-ptr})
1987 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{@acsmem{}}}
1988 @c obstack_init @mtsrace:obstack-ptr @acsmem
1989 @c  _obstack_begin @acsmem
1990 @c    chunkfun = obstack_chunk_alloc (suggested malloc)
1991 @c    freefun = obstack_chunk_free (suggested free)
1992 @c   *chunkfun @acsmem
1993 @c    obstack_chunk_alloc user-supplied
1994 @c   *obstack_alloc_failed_handler user-supplied
1995 @c    -> print_and_abort (default)
1997 @c print_and_abort
1998 @c  _ dup @ascuintl
1999 @c  fxprintf dup @asucorrupt @aculock @acucorrupt
2000 @c  exit @acucorrupt?
2001 Initialize obstack @var{obstack-ptr} for allocation of objects.  This
2002 function calls the obstack's @code{obstack_chunk_alloc} function.  If
2003 allocation of memory fails, the function pointed to by
2004 @code{obstack_alloc_failed_handler} is called.  The @code{obstack_init}
2005 function always returns 1 (Compatibility notice: Former versions of
2006 obstack returned 0 if allocation failed).
2007 @end deftypefun
2009 Here are two examples of how to allocate the space for an obstack and
2010 initialize it.  First, an obstack that is a static variable:
2012 @smallexample
2013 static struct obstack myobstack;
2014 @dots{}
2015 obstack_init (&myobstack);
2016 @end smallexample
2018 @noindent
2019 Second, an obstack that is itself dynamically allocated:
2021 @smallexample
2022 struct obstack *myobstack_ptr
2023   = (struct obstack *) xmalloc (sizeof (struct obstack));
2025 obstack_init (myobstack_ptr);
2026 @end smallexample
2028 @comment obstack.h
2029 @comment GNU
2030 @defvar obstack_alloc_failed_handler
2031 The value of this variable is a pointer to a function that
2032 @code{obstack} uses when @code{obstack_chunk_alloc} fails to allocate
2033 memory.  The default action is to print a message and abort.
2034 You should supply a function that either calls @code{exit}
2035 (@pxref{Program Termination}) or @code{longjmp} (@pxref{Non-Local
2036 Exits}) and doesn't return.
2038 @smallexample
2039 void my_obstack_alloc_failed (void)
2040 @dots{}
2041 obstack_alloc_failed_handler = &my_obstack_alloc_failed;
2042 @end smallexample
2044 @end defvar
2046 @node Allocation in an Obstack
2047 @subsubsection Allocation in an Obstack
2048 @cindex allocation (obstacks)
2050 The most direct way to allocate an object in an obstack is with
2051 @code{obstack_alloc}, which is invoked almost like @code{malloc}.
2053 @comment obstack.h
2054 @comment GNU
2055 @deftypefun {void *} obstack_alloc (struct obstack *@var{obstack-ptr}, int @var{size})
2056 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2057 @c obstack_alloc @mtsrace:obstack-ptr @acucorrupt @acsmem
2058 @c  obstack_blank dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2059 @c  obstack_finish dup @mtsrace:obstack-ptr @acucorrupt
2060 This allocates an uninitialized block of @var{size} bytes in an obstack
2061 and returns its address.  Here @var{obstack-ptr} specifies which obstack
2062 to allocate the block in; it is the address of the @code{struct obstack}
2063 object which represents the obstack.  Each obstack function or macro
2064 requires you to specify an @var{obstack-ptr} as the first argument.
2066 This function calls the obstack's @code{obstack_chunk_alloc} function if
2067 it needs to allocate a new chunk of memory; it calls
2068 @code{obstack_alloc_failed_handler} if allocation of memory by
2069 @code{obstack_chunk_alloc} failed.
2070 @end deftypefun
2072 For example, here is a function that allocates a copy of a string @var{str}
2073 in a specific obstack, which is in the variable @code{string_obstack}:
2075 @smallexample
2076 struct obstack string_obstack;
2078 char *
2079 copystring (char *string)
2081   size_t len = strlen (string) + 1;
2082   char *s = (char *) obstack_alloc (&string_obstack, len);
2083   memcpy (s, string, len);
2084   return s;
2086 @end smallexample
2088 To allocate a block with specified contents, use the function
2089 @code{obstack_copy}, declared like this:
2091 @comment obstack.h
2092 @comment GNU
2093 @deftypefun {void *} obstack_copy (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2094 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2095 @c obstack_copy @mtsrace:obstack-ptr @acucorrupt @acsmem
2096 @c  obstack_grow dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2097 @c  obstack_finish dup @mtsrace:obstack-ptr @acucorrupt
2098 This allocates a block and initializes it by copying @var{size}
2099 bytes of data starting at @var{address}.  It calls
2100 @code{obstack_alloc_failed_handler} if allocation of memory by
2101 @code{obstack_chunk_alloc} failed.
2102 @end deftypefun
2104 @comment obstack.h
2105 @comment GNU
2106 @deftypefun {void *} obstack_copy0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2107 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2108 @c obstack_copy0 @mtsrace:obstack-ptr @acucorrupt @acsmem
2109 @c  obstack_grow0 dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2110 @c  obstack_finish dup @mtsrace:obstack-ptr @acucorrupt
2111 Like @code{obstack_copy}, but appends an extra byte containing a null
2112 character.  This extra byte is not counted in the argument @var{size}.
2113 @end deftypefun
2115 The @code{obstack_copy0} function is convenient for copying a sequence
2116 of characters into an obstack as a null-terminated string.  Here is an
2117 example of its use:
2119 @smallexample
2120 char *
2121 obstack_savestring (char *addr, int size)
2123   return obstack_copy0 (&myobstack, addr, size);
2125 @end smallexample
2127 @noindent
2128 Contrast this with the previous example of @code{savestring} using
2129 @code{malloc} (@pxref{Basic Allocation}).
2131 @node Freeing Obstack Objects
2132 @subsubsection Freeing Objects in an Obstack
2133 @cindex freeing (obstacks)
2135 To free an object allocated in an obstack, use the function
2136 @code{obstack_free}.  Since the obstack is a stack of objects, freeing
2137 one object automatically frees all other objects allocated more recently
2138 in the same obstack.
2140 @comment obstack.h
2141 @comment GNU
2142 @deftypefun void obstack_free (struct obstack *@var{obstack-ptr}, void *@var{object})
2143 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{}}}
2144 @c obstack_free @mtsrace:obstack-ptr @acucorrupt
2145 @c  (obstack_free) @mtsrace:obstack-ptr @acucorrupt
2146 @c   *freefun dup user-supplied
2147 If @var{object} is a null pointer, everything allocated in the obstack
2148 is freed.  Otherwise, @var{object} must be the address of an object
2149 allocated in the obstack.  Then @var{object} is freed, along with
2150 everything allocated in @var{obstack-ptr} since @var{object}.
2151 @end deftypefun
2153 Note that if @var{object} is a null pointer, the result is an
2154 uninitialized obstack.  To free all memory in an obstack but leave it
2155 valid for further allocation, call @code{obstack_free} with the address
2156 of the first object allocated on the obstack:
2158 @smallexample
2159 obstack_free (obstack_ptr, first_object_allocated_ptr);
2160 @end smallexample
2162 Recall that the objects in an obstack are grouped into chunks.  When all
2163 the objects in a chunk become free, the obstack library automatically
2164 frees the chunk (@pxref{Preparing for Obstacks}).  Then other
2165 obstacks, or non-obstack allocation, can reuse the space of the chunk.
2167 @node Obstack Functions
2168 @subsubsection Obstack Functions and Macros
2169 @cindex macros
2171 The interfaces for using obstacks may be defined either as functions or
2172 as macros, depending on the compiler.  The obstack facility works with
2173 all C compilers, including both @w{ISO C} and traditional C, but there are
2174 precautions you must take if you plan to use compilers other than GNU C.
2176 If you are using an old-fashioned @w{non-ISO C} compiler, all the obstack
2177 ``functions'' are actually defined only as macros.  You can call these
2178 macros like functions, but you cannot use them in any other way (for
2179 example, you cannot take their address).
2181 Calling the macros requires a special precaution: namely, the first
2182 operand (the obstack pointer) may not contain any side effects, because
2183 it may be computed more than once.  For example, if you write this:
2185 @smallexample
2186 obstack_alloc (get_obstack (), 4);
2187 @end smallexample
2189 @noindent
2190 you will find that @code{get_obstack} may be called several times.
2191 If you use @code{*obstack_list_ptr++} as the obstack pointer argument,
2192 you will get very strange results since the incrementation may occur
2193 several times.
2195 In @w{ISO C}, each function has both a macro definition and a function
2196 definition.  The function definition is used if you take the address of the
2197 function without calling it.  An ordinary call uses the macro definition by
2198 default, but you can request the function definition instead by writing the
2199 function name in parentheses, as shown here:
2201 @smallexample
2202 char *x;
2203 void *(*funcp) ();
2204 /* @r{Use the macro}.  */
2205 x = (char *) obstack_alloc (obptr, size);
2206 /* @r{Call the function}.  */
2207 x = (char *) (obstack_alloc) (obptr, size);
2208 /* @r{Take the address of the function}.  */
2209 funcp = obstack_alloc;
2210 @end smallexample
2212 @noindent
2213 This is the same situation that exists in @w{ISO C} for the standard library
2214 functions.  @xref{Macro Definitions}.
2216 @strong{Warning:} When you do use the macros, you must observe the
2217 precaution of avoiding side effects in the first operand, even in @w{ISO C}.
2219 If you use the GNU C compiler, this precaution is not necessary, because
2220 various language extensions in GNU C permit defining the macros so as to
2221 compute each argument only once.
2223 @node Growing Objects
2224 @subsubsection Growing Objects
2225 @cindex growing objects (in obstacks)
2226 @cindex changing the size of a block (obstacks)
2228 Because memory in obstack chunks is used sequentially, it is possible to
2229 build up an object step by step, adding one or more bytes at a time to the
2230 end of the object.  With this technique, you do not need to know how much
2231 data you will put in the object until you come to the end of it.  We call
2232 this the technique of @dfn{growing objects}.  The special functions
2233 for adding data to the growing object are described in this section.
2235 You don't need to do anything special when you start to grow an object.
2236 Using one of the functions to add data to the object automatically
2237 starts it.  However, it is necessary to say explicitly when the object is
2238 finished.  This is done with the function @code{obstack_finish}.
2240 The actual address of the object thus built up is not known until the
2241 object is finished.  Until then, it always remains possible that you will
2242 add so much data that the object must be copied into a new chunk.
2244 While the obstack is in use for a growing object, you cannot use it for
2245 ordinary allocation of another object.  If you try to do so, the space
2246 already added to the growing object will become part of the other object.
2248 @comment obstack.h
2249 @comment GNU
2250 @deftypefun void obstack_blank (struct obstack *@var{obstack-ptr}, int @var{size})
2251 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2252 @c obstack_blank @mtsrace:obstack-ptr @acucorrupt @acsmem
2253 @c  _obstack_newchunk @mtsrace:obstack-ptr @acucorrupt @acsmem
2254 @c   *chunkfun dup @acsmem
2255 @c   *obstack_alloc_failed_handler dup user-supplied
2256 @c   *freefun
2257 @c  obstack_blank_fast dup @mtsrace:obstack-ptr
2258 The most basic function for adding to a growing object is
2259 @code{obstack_blank}, which adds space without initializing it.
2260 @end deftypefun
2262 @comment obstack.h
2263 @comment GNU
2264 @deftypefun void obstack_grow (struct obstack *@var{obstack-ptr}, void *@var{data}, int @var{size})
2265 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2266 @c obstack_grow @mtsrace:obstack-ptr @acucorrupt @acsmem
2267 @c  _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2268 @c  memcpy ok
2269 To add a block of initialized space, use @code{obstack_grow}, which is
2270 the growing-object analogue of @code{obstack_copy}.  It adds @var{size}
2271 bytes of data to the growing object, copying the contents from
2272 @var{data}.
2273 @end deftypefun
2275 @comment obstack.h
2276 @comment GNU
2277 @deftypefun void obstack_grow0 (struct obstack *@var{obstack-ptr}, void *@var{data}, int @var{size})
2278 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2279 @c obstack_grow0 @mtsrace:obstack-ptr @acucorrupt @acsmem
2280 @c   (no sequence point between storing NUL and incrementing next_free)
2281 @c   (multiple changes to next_free => @acucorrupt)
2282 @c  _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2283 @c  memcpy ok
2284 This is the growing-object analogue of @code{obstack_copy0}.  It adds
2285 @var{size} bytes copied from @var{data}, followed by an additional null
2286 character.
2287 @end deftypefun
2289 @comment obstack.h
2290 @comment GNU
2291 @deftypefun void obstack_1grow (struct obstack *@var{obstack-ptr}, char @var{c})
2292 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2293 @c obstack_1grow @mtsrace:obstack-ptr @acucorrupt @acsmem
2294 @c  _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2295 @c  obstack_1grow_fast dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2296 To add one character at a time, use the function @code{obstack_1grow}.
2297 It adds a single byte containing @var{c} to the growing object.
2298 @end deftypefun
2300 @comment obstack.h
2301 @comment GNU
2302 @deftypefun void obstack_ptr_grow (struct obstack *@var{obstack-ptr}, void *@var{data})
2303 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2304 @c obstack_ptr_grow @mtsrace:obstack-ptr @acucorrupt @acsmem
2305 @c  _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2306 @c  obstack_ptr_grow_fast dup @mtsrace:obstack-ptr
2307 Adding the value of a pointer one can use the function
2308 @code{obstack_ptr_grow}.  It adds @code{sizeof (void *)} bytes
2309 containing the value of @var{data}.
2310 @end deftypefun
2312 @comment obstack.h
2313 @comment GNU
2314 @deftypefun void obstack_int_grow (struct obstack *@var{obstack-ptr}, int @var{data})
2315 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2316 @c obstack_int_grow @mtsrace:obstack-ptr @acucorrupt @acsmem
2317 @c  _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2318 @c  obstack_int_grow_fast dup @mtsrace:obstack-ptr
2319 A single value of type @code{int} can be added by using the
2320 @code{obstack_int_grow} function.  It adds @code{sizeof (int)} bytes to
2321 the growing object and initializes them with the value of @var{data}.
2322 @end deftypefun
2324 @comment obstack.h
2325 @comment GNU
2326 @deftypefun {void *} obstack_finish (struct obstack *@var{obstack-ptr})
2327 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{}}}
2328 @c obstack_finish @mtsrace:obstack-ptr @acucorrupt
2329 When you are finished growing the object, use the function
2330 @code{obstack_finish} to close it off and return its final address.
2332 Once you have finished the object, the obstack is available for ordinary
2333 allocation or for growing another object.
2335 This function can return a null pointer under the same conditions as
2336 @code{obstack_alloc} (@pxref{Allocation in an Obstack}).
2337 @end deftypefun
2339 When you build an object by growing it, you will probably need to know
2340 afterward how long it became.  You need not keep track of this as you grow
2341 the object, because you can find out the length from the obstack just
2342 before finishing the object with the function @code{obstack_object_size},
2343 declared as follows:
2345 @comment obstack.h
2346 @comment GNU
2347 @deftypefun int obstack_object_size (struct obstack *@var{obstack-ptr})
2348 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
2349 This function returns the current size of the growing object, in bytes.
2350 Remember to call this function @emph{before} finishing the object.
2351 After it is finished, @code{obstack_object_size} will return zero.
2352 @end deftypefun
2354 If you have started growing an object and wish to cancel it, you should
2355 finish it and then free it, like this:
2357 @smallexample
2358 obstack_free (obstack_ptr, obstack_finish (obstack_ptr));
2359 @end smallexample
2361 @noindent
2362 This has no effect if no object was growing.
2364 @cindex shrinking objects
2365 You can use @code{obstack_blank} with a negative size argument to make
2366 the current object smaller.  Just don't try to shrink it beyond zero
2367 length---there's no telling what will happen if you do that.
2369 @node Extra Fast Growing
2370 @subsubsection Extra Fast Growing Objects
2371 @cindex efficiency and obstacks
2373 The usual functions for growing objects incur overhead for checking
2374 whether there is room for the new growth in the current chunk.  If you
2375 are frequently constructing objects in small steps of growth, this
2376 overhead can be significant.
2378 You can reduce the overhead by using special ``fast growth''
2379 functions that grow the object without checking.  In order to have a
2380 robust program, you must do the checking yourself.  If you do this checking
2381 in the simplest way each time you are about to add data to the object, you
2382 have not saved anything, because that is what the ordinary growth
2383 functions do.  But if you can arrange to check less often, or check
2384 more efficiently, then you make the program faster.
2386 The function @code{obstack_room} returns the amount of room available
2387 in the current chunk.  It is declared as follows:
2389 @comment obstack.h
2390 @comment GNU
2391 @deftypefun int obstack_room (struct obstack *@var{obstack-ptr})
2392 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
2393 This returns the number of bytes that can be added safely to the current
2394 growing object (or to an object about to be started) in obstack
2395 @var{obstack-ptr} using the fast growth functions.
2396 @end deftypefun
2398 While you know there is room, you can use these fast growth functions
2399 for adding data to a growing object:
2401 @comment obstack.h
2402 @comment GNU
2403 @deftypefun void obstack_1grow_fast (struct obstack *@var{obstack-ptr}, char @var{c})
2404 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2405 @c obstack_1grow_fast @mtsrace:obstack-ptr @acucorrupt @acsmem
2406 @c   (no sequence point between copying c and incrementing next_free)
2407 The function @code{obstack_1grow_fast} adds one byte containing the
2408 character @var{c} to the growing object in obstack @var{obstack-ptr}.
2409 @end deftypefun
2411 @comment obstack.h
2412 @comment GNU
2413 @deftypefun void obstack_ptr_grow_fast (struct obstack *@var{obstack-ptr}, void *@var{data})
2414 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
2415 @c obstack_ptr_grow_fast @mtsrace:obstack-ptr
2416 The function @code{obstack_ptr_grow_fast} adds @code{sizeof (void *)}
2417 bytes containing the value of @var{data} to the growing object in
2418 obstack @var{obstack-ptr}.
2419 @end deftypefun
2421 @comment obstack.h
2422 @comment GNU
2423 @deftypefun void obstack_int_grow_fast (struct obstack *@var{obstack-ptr}, int @var{data})
2424 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
2425 @c obstack_int_grow_fast @mtsrace:obstack-ptr
2426 The function @code{obstack_int_grow_fast} adds @code{sizeof (int)} bytes
2427 containing the value of @var{data} to the growing object in obstack
2428 @var{obstack-ptr}.
2429 @end deftypefun
2431 @comment obstack.h
2432 @comment GNU
2433 @deftypefun void obstack_blank_fast (struct obstack *@var{obstack-ptr}, int @var{size})
2434 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
2435 @c obstack_blank_fast @mtsrace:obstack-ptr
2436 The function @code{obstack_blank_fast} adds @var{size} bytes to the
2437 growing object in obstack @var{obstack-ptr} without initializing them.
2438 @end deftypefun
2440 When you check for space using @code{obstack_room} and there is not
2441 enough room for what you want to add, the fast growth functions
2442 are not safe.  In this case, simply use the corresponding ordinary
2443 growth function instead.  Very soon this will copy the object to a
2444 new chunk; then there will be lots of room available again.
2446 So, each time you use an ordinary growth function, check afterward for
2447 sufficient space using @code{obstack_room}.  Once the object is copied
2448 to a new chunk, there will be plenty of space again, so the program will
2449 start using the fast growth functions again.
2451 Here is an example:
2453 @smallexample
2454 @group
2455 void
2456 add_string (struct obstack *obstack, const char *ptr, int len)
2458   while (len > 0)
2459     @{
2460       int room = obstack_room (obstack);
2461       if (room == 0)
2462         @{
2463           /* @r{Not enough room.  Add one character slowly,}
2464              @r{which may copy to a new chunk and make room.}  */
2465           obstack_1grow (obstack, *ptr++);
2466           len--;
2467         @}
2468       else
2469         @{
2470           if (room > len)
2471             room = len;
2472           /* @r{Add fast as much as we have room for.} */
2473           len -= room;
2474           while (room-- > 0)
2475             obstack_1grow_fast (obstack, *ptr++);
2476         @}
2477     @}
2479 @end group
2480 @end smallexample
2482 @node Status of an Obstack
2483 @subsubsection Status of an Obstack
2484 @cindex obstack status
2485 @cindex status of obstack
2487 Here are functions that provide information on the current status of
2488 allocation in an obstack.  You can use them to learn about an object while
2489 still growing it.
2491 @comment obstack.h
2492 @comment GNU
2493 @deftypefun {void *} obstack_base (struct obstack *@var{obstack-ptr})
2494 @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acsafe{}}
2495 This function returns the tentative address of the beginning of the
2496 currently growing object in @var{obstack-ptr}.  If you finish the object
2497 immediately, it will have that address.  If you make it larger first, it
2498 may outgrow the current chunk---then its address will change!
2500 If no object is growing, this value says where the next object you
2501 allocate will start (once again assuming it fits in the current
2502 chunk).
2503 @end deftypefun
2505 @comment obstack.h
2506 @comment GNU
2507 @deftypefun {void *} obstack_next_free (struct obstack *@var{obstack-ptr})
2508 @safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acsafe{}}
2509 This function returns the address of the first free byte in the current
2510 chunk of obstack @var{obstack-ptr}.  This is the end of the currently
2511 growing object.  If no object is growing, @code{obstack_next_free}
2512 returns the same value as @code{obstack_base}.
2513 @end deftypefun
2515 @comment obstack.h
2516 @comment GNU
2517 @deftypefun int obstack_object_size (struct obstack *@var{obstack-ptr})
2518 @c dup
2519 @safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
2520 This function returns the size in bytes of the currently growing object.
2521 This is equivalent to
2523 @smallexample
2524 obstack_next_free (@var{obstack-ptr}) - obstack_base (@var{obstack-ptr})
2525 @end smallexample
2526 @end deftypefun
2528 @node Obstacks Data Alignment
2529 @subsubsection Alignment of Data in Obstacks
2530 @cindex alignment (in obstacks)
2532 Each obstack has an @dfn{alignment boundary}; each object allocated in
2533 the obstack automatically starts on an address that is a multiple of the
2534 specified boundary.  By default, this boundary is aligned so that
2535 the object can hold any type of data.
2537 To access an obstack's alignment boundary, use the macro
2538 @code{obstack_alignment_mask}, whose function prototype looks like
2539 this:
2541 @comment obstack.h
2542 @comment GNU
2543 @deftypefn Macro int obstack_alignment_mask (struct obstack *@var{obstack-ptr})
2544 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2545 The value is a bit mask; a bit that is 1 indicates that the corresponding
2546 bit in the address of an object should be 0.  The mask value should be one
2547 less than a power of 2; the effect is that all object addresses are
2548 multiples of that power of 2.  The default value of the mask is a value
2549 that allows aligned objects to hold any type of data: for example, if
2550 its value is 3, any type of data can be stored at locations whose
2551 addresses are multiples of 4.  A mask value of 0 means an object can start
2552 on any multiple of 1 (that is, no alignment is required).
2554 The expansion of the macro @code{obstack_alignment_mask} is an lvalue,
2555 so you can alter the mask by assignment.  For example, this statement:
2557 @smallexample
2558 obstack_alignment_mask (obstack_ptr) = 0;
2559 @end smallexample
2561 @noindent
2562 has the effect of turning off alignment processing in the specified obstack.
2563 @end deftypefn
2565 Note that a change in alignment mask does not take effect until
2566 @emph{after} the next time an object is allocated or finished in the
2567 obstack.  If you are not growing an object, you can make the new
2568 alignment mask take effect immediately by calling @code{obstack_finish}.
2569 This will finish a zero-length object and then do proper alignment for
2570 the next object.
2572 @node Obstack Chunks
2573 @subsubsection Obstack Chunks
2574 @cindex efficiency of chunks
2575 @cindex chunks
2577 Obstacks work by allocating space for themselves in large chunks, and
2578 then parceling out space in the chunks to satisfy your requests.  Chunks
2579 are normally 4096 bytes long unless you specify a different chunk size.
2580 The chunk size includes 8 bytes of overhead that are not actually used
2581 for storing objects.  Regardless of the specified size, longer chunks
2582 will be allocated when necessary for long objects.
2584 The obstack library allocates chunks by calling the function
2585 @code{obstack_chunk_alloc}, which you must define.  When a chunk is no
2586 longer needed because you have freed all the objects in it, the obstack
2587 library frees the chunk by calling @code{obstack_chunk_free}, which you
2588 must also define.
2590 These two must be defined (as macros) or declared (as functions) in each
2591 source file that uses @code{obstack_init} (@pxref{Creating Obstacks}).
2592 Most often they are defined as macros like this:
2594 @smallexample
2595 #define obstack_chunk_alloc malloc
2596 #define obstack_chunk_free free
2597 @end smallexample
2599 Note that these are simple macros (no arguments).  Macro definitions with
2600 arguments will not work!  It is necessary that @code{obstack_chunk_alloc}
2601 or @code{obstack_chunk_free}, alone, expand into a function name if it is
2602 not itself a function name.
2604 If you allocate chunks with @code{malloc}, the chunk size should be a
2605 power of 2.  The default chunk size, 4096, was chosen because it is long
2606 enough to satisfy many typical requests on the obstack yet short enough
2607 not to waste too much memory in the portion of the last chunk not yet used.
2609 @comment obstack.h
2610 @comment GNU
2611 @deftypefn Macro int obstack_chunk_size (struct obstack *@var{obstack-ptr})
2612 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2613 This returns the chunk size of the given obstack.
2614 @end deftypefn
2616 Since this macro expands to an lvalue, you can specify a new chunk size by
2617 assigning it a new value.  Doing so does not affect the chunks already
2618 allocated, but will change the size of chunks allocated for that particular
2619 obstack in the future.  It is unlikely to be useful to make the chunk size
2620 smaller, but making it larger might improve efficiency if you are
2621 allocating many objects whose size is comparable to the chunk size.  Here
2622 is how to do so cleanly:
2624 @smallexample
2625 if (obstack_chunk_size (obstack_ptr) < @var{new-chunk-size})
2626   obstack_chunk_size (obstack_ptr) = @var{new-chunk-size};
2627 @end smallexample
2629 @node Summary of Obstacks
2630 @subsubsection Summary of Obstack Functions
2632 Here is a summary of all the functions associated with obstacks.  Each
2633 takes the address of an obstack (@code{struct obstack *}) as its first
2634 argument.
2636 @table @code
2637 @item void obstack_init (struct obstack *@var{obstack-ptr})
2638 Initialize use of an obstack.  @xref{Creating Obstacks}.
2640 @item void *obstack_alloc (struct obstack *@var{obstack-ptr}, int @var{size})
2641 Allocate an object of @var{size} uninitialized bytes.
2642 @xref{Allocation in an Obstack}.
2644 @item void *obstack_copy (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2645 Allocate an object of @var{size} bytes, with contents copied from
2646 @var{address}.  @xref{Allocation in an Obstack}.
2648 @item void *obstack_copy0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2649 Allocate an object of @var{size}+1 bytes, with @var{size} of them copied
2650 from @var{address}, followed by a null character at the end.
2651 @xref{Allocation in an Obstack}.
2653 @item void obstack_free (struct obstack *@var{obstack-ptr}, void *@var{object})
2654 Free @var{object} (and everything allocated in the specified obstack
2655 more recently than @var{object}).  @xref{Freeing Obstack Objects}.
2657 @item void obstack_blank (struct obstack *@var{obstack-ptr}, int @var{size})
2658 Add @var{size} uninitialized bytes to a growing object.
2659 @xref{Growing Objects}.
2661 @item void obstack_grow (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2662 Add @var{size} bytes, copied from @var{address}, to a growing object.
2663 @xref{Growing Objects}.
2665 @item void obstack_grow0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2666 Add @var{size} bytes, copied from @var{address}, to a growing object,
2667 and then add another byte containing a null character.  @xref{Growing
2668 Objects}.
2670 @item void obstack_1grow (struct obstack *@var{obstack-ptr}, char @var{data-char})
2671 Add one byte containing @var{data-char} to a growing object.
2672 @xref{Growing Objects}.
2674 @item void *obstack_finish (struct obstack *@var{obstack-ptr})
2675 Finalize the object that is growing and return its permanent address.
2676 @xref{Growing Objects}.
2678 @item int obstack_object_size (struct obstack *@var{obstack-ptr})
2679 Get the current size of the currently growing object.  @xref{Growing
2680 Objects}.
2682 @item void obstack_blank_fast (struct obstack *@var{obstack-ptr}, int @var{size})
2683 Add @var{size} uninitialized bytes to a growing object without checking
2684 that there is enough room.  @xref{Extra Fast Growing}.
2686 @item void obstack_1grow_fast (struct obstack *@var{obstack-ptr}, char @var{data-char})
2687 Add one byte containing @var{data-char} to a growing object without
2688 checking that there is enough room.  @xref{Extra Fast Growing}.
2690 @item int obstack_room (struct obstack *@var{obstack-ptr})
2691 Get the amount of room now available for growing the current object.
2692 @xref{Extra Fast Growing}.
2694 @item int obstack_alignment_mask (struct obstack *@var{obstack-ptr})
2695 The mask used for aligning the beginning of an object.  This is an
2696 lvalue.  @xref{Obstacks Data Alignment}.
2698 @item int obstack_chunk_size (struct obstack *@var{obstack-ptr})
2699 The size for allocating chunks.  This is an lvalue.  @xref{Obstack Chunks}.
2701 @item void *obstack_base (struct obstack *@var{obstack-ptr})
2702 Tentative starting address of the currently growing object.
2703 @xref{Status of an Obstack}.
2705 @item void *obstack_next_free (struct obstack *@var{obstack-ptr})
2706 Address just after the end of the currently growing object.
2707 @xref{Status of an Obstack}.
2708 @end table
2710 @node Variable Size Automatic
2711 @subsection Automatic Storage with Variable Size
2712 @cindex automatic freeing
2713 @cindex @code{alloca} function
2714 @cindex automatic storage with variable size
2716 The function @code{alloca} supports a kind of half-dynamic allocation in
2717 which blocks are allocated dynamically but freed automatically.
2719 Allocating a block with @code{alloca} is an explicit action; you can
2720 allocate as many blocks as you wish, and compute the size at run time.  But
2721 all the blocks are freed when you exit the function that @code{alloca} was
2722 called from, just as if they were automatic variables declared in that
2723 function.  There is no way to free the space explicitly.
2725 The prototype for @code{alloca} is in @file{stdlib.h}.  This function is
2726 a BSD extension.
2727 @pindex stdlib.h
2729 @comment stdlib.h
2730 @comment GNU, BSD
2731 @deftypefun {void *} alloca (size_t @var{size})
2732 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2733 The return value of @code{alloca} is the address of a block of @var{size}
2734 bytes of memory, allocated in the stack frame of the calling function.
2735 @end deftypefun
2737 Do not use @code{alloca} inside the arguments of a function call---you
2738 will get unpredictable results, because the stack space for the
2739 @code{alloca} would appear on the stack in the middle of the space for
2740 the function arguments.  An example of what to avoid is @code{foo (x,
2741 alloca (4), y)}.
2742 @c This might get fixed in future versions of GCC, but that won't make
2743 @c it safe with compilers generally.
2745 @menu
2746 * Alloca Example::              Example of using @code{alloca}.
2747 * Advantages of Alloca::        Reasons to use @code{alloca}.
2748 * Disadvantages of Alloca::     Reasons to avoid @code{alloca}.
2749 * GNU C Variable-Size Arrays::  Only in GNU C, here is an alternative
2750                                  method of allocating dynamically and
2751                                  freeing automatically.
2752 @end menu
2754 @node Alloca Example
2755 @subsubsection @code{alloca} Example
2757 As an example of the use of @code{alloca}, here is a function that opens
2758 a file name made from concatenating two argument strings, and returns a
2759 file descriptor or minus one signifying failure:
2761 @smallexample
2763 open2 (char *str1, char *str2, int flags, int mode)
2765   char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
2766   stpcpy (stpcpy (name, str1), str2);
2767   return open (name, flags, mode);
2769 @end smallexample
2771 @noindent
2772 Here is how you would get the same results with @code{malloc} and
2773 @code{free}:
2775 @smallexample
2777 open2 (char *str1, char *str2, int flags, int mode)
2779   char *name = (char *) malloc (strlen (str1) + strlen (str2) + 1);
2780   int desc;
2781   if (name == 0)
2782     fatal ("virtual memory exceeded");
2783   stpcpy (stpcpy (name, str1), str2);
2784   desc = open (name, flags, mode);
2785   free (name);
2786   return desc;
2788 @end smallexample
2790 As you can see, it is simpler with @code{alloca}.  But @code{alloca} has
2791 other, more important advantages, and some disadvantages.
2793 @node Advantages of Alloca
2794 @subsubsection Advantages of @code{alloca}
2796 Here are the reasons why @code{alloca} may be preferable to @code{malloc}:
2798 @itemize @bullet
2799 @item
2800 Using @code{alloca} wastes very little space and is very fast.  (It is
2801 open-coded by the GNU C compiler.)
2803 @item
2804 Since @code{alloca} does not have separate pools for different sizes of
2805 blocks, space used for any size block can be reused for any other size.
2806 @code{alloca} does not cause memory fragmentation.
2808 @item
2809 @cindex longjmp
2810 Nonlocal exits done with @code{longjmp} (@pxref{Non-Local Exits})
2811 automatically free the space allocated with @code{alloca} when they exit
2812 through the function that called @code{alloca}.  This is the most
2813 important reason to use @code{alloca}.
2815 To illustrate this, suppose you have a function
2816 @code{open_or_report_error} which returns a descriptor, like
2817 @code{open}, if it succeeds, but does not return to its caller if it
2818 fails.  If the file cannot be opened, it prints an error message and
2819 jumps out to the command level of your program using @code{longjmp}.
2820 Let's change @code{open2} (@pxref{Alloca Example}) to use this
2821 subroutine:@refill
2823 @smallexample
2825 open2 (char *str1, char *str2, int flags, int mode)
2827   char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
2828   stpcpy (stpcpy (name, str1), str2);
2829   return open_or_report_error (name, flags, mode);
2831 @end smallexample
2833 @noindent
2834 Because of the way @code{alloca} works, the memory it allocates is
2835 freed even when an error occurs, with no special effort required.
2837 By contrast, the previous definition of @code{open2} (which uses
2838 @code{malloc} and @code{free}) would develop a memory leak if it were
2839 changed in this way.  Even if you are willing to make more changes to
2840 fix it, there is no easy way to do so.
2841 @end itemize
2843 @node Disadvantages of Alloca
2844 @subsubsection Disadvantages of @code{alloca}
2846 @cindex @code{alloca} disadvantages
2847 @cindex disadvantages of @code{alloca}
2848 These are the disadvantages of @code{alloca} in comparison with
2849 @code{malloc}:
2851 @itemize @bullet
2852 @item
2853 If you try to allocate more memory than the machine can provide, you
2854 don't get a clean error message.  Instead you get a fatal signal like
2855 the one you would get from an infinite recursion; probably a
2856 segmentation violation (@pxref{Program Error Signals}).
2858 @item
2859 Some @nongnusystems{} fail to support @code{alloca}, so it is less
2860 portable.  However, a slower emulation of @code{alloca} written in C
2861 is available for use on systems with this deficiency.
2862 @end itemize
2864 @node GNU C Variable-Size Arrays
2865 @subsubsection GNU C Variable-Size Arrays
2866 @cindex variable-sized arrays
2868 In GNU C, you can replace most uses of @code{alloca} with an array of
2869 variable size.  Here is how @code{open2} would look then:
2871 @smallexample
2872 int open2 (char *str1, char *str2, int flags, int mode)
2874   char name[strlen (str1) + strlen (str2) + 1];
2875   stpcpy (stpcpy (name, str1), str2);
2876   return open (name, flags, mode);
2878 @end smallexample
2880 But @code{alloca} is not always equivalent to a variable-sized array, for
2881 several reasons:
2883 @itemize @bullet
2884 @item
2885 A variable size array's space is freed at the end of the scope of the
2886 name of the array.  The space allocated with @code{alloca}
2887 remains until the end of the function.
2889 @item
2890 It is possible to use @code{alloca} within a loop, allocating an
2891 additional block on each iteration.  This is impossible with
2892 variable-sized arrays.
2893 @end itemize
2895 @strong{NB:} If you mix use of @code{alloca} and variable-sized arrays
2896 within one function, exiting a scope in which a variable-sized array was
2897 declared frees all blocks allocated with @code{alloca} during the
2898 execution of that scope.
2901 @node Resizing the Data Segment
2902 @section Resizing the Data Segment
2904 The symbols in this section are declared in @file{unistd.h}.
2906 You will not normally use the functions in this section, because the
2907 functions described in @ref{Memory Allocation} are easier to use.  Those
2908 are interfaces to a @glibcadj{} memory allocator that uses the
2909 functions below itself.  The functions below are simple interfaces to
2910 system calls.
2912 @comment unistd.h
2913 @comment BSD
2914 @deftypefun int brk (void *@var{addr})
2915 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2917 @code{brk} sets the high end of the calling process' data segment to
2918 @var{addr}.
2920 The address of the end of a segment is defined to be the address of the
2921 last byte in the segment plus 1.
2923 The function has no effect if @var{addr} is lower than the low end of
2924 the data segment.  (This is considered success, by the way.)
2926 The function fails if it would cause the data segment to overlap another
2927 segment or exceed the process' data storage limit (@pxref{Limits on
2928 Resources}).
2930 The function is named for a common historical case where data storage
2931 and the stack are in the same segment.  Data storage allocation grows
2932 upward from the bottom of the segment while the stack grows downward
2933 toward it from the top of the segment and the curtain between them is
2934 called the @dfn{break}.
2936 The return value is zero on success.  On failure, the return value is
2937 @code{-1} and @code{errno} is set accordingly.  The following @code{errno}
2938 values are specific to this function:
2940 @table @code
2941 @item ENOMEM
2942 The request would cause the data segment to overlap another segment or
2943 exceed the process' data storage limit.
2944 @end table
2946 @c The Brk system call in Linux (as opposed to the GNU C Library function)
2947 @c is considerably different.  It always returns the new end of the data
2948 @c segment, whether it succeeds or fails.  The GNU C library Brk determines
2949 @c it's a failure if and only if the system call returns an address less
2950 @c than the address requested.
2952 @end deftypefun
2955 @comment unistd.h
2956 @comment BSD
2957 @deftypefun void *sbrk (ptrdiff_t @var{delta})
2958 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2960 This function is the same as @code{brk} except that you specify the new
2961 end of the data segment as an offset @var{delta} from the current end
2962 and on success the return value is the address of the resulting end of
2963 the data segment instead of zero.
2965 This means you can use @samp{sbrk(0)} to find out what the current end
2966 of the data segment is.
2968 @end deftypefun
2972 @node Locking Pages
2973 @section Locking Pages
2974 @cindex locking pages
2975 @cindex memory lock
2976 @cindex paging
2978 You can tell the system to associate a particular virtual memory page
2979 with a real page frame and keep it that way --- i.e., cause the page to
2980 be paged in if it isn't already and mark it so it will never be paged
2981 out and consequently will never cause a page fault.  This is called
2982 @dfn{locking} a page.
2984 The functions in this chapter lock and unlock the calling process'
2985 pages.
2987 @menu
2988 * Why Lock Pages::                Reasons to read this section.
2989 * Locked Memory Details::         Everything you need to know locked
2990                                     memory
2991 * Page Lock Functions::           Here's how to do it.
2992 @end menu
2994 @node Why Lock Pages
2995 @subsection Why Lock Pages
2997 Because page faults cause paged out pages to be paged in transparently,
2998 a process rarely needs to be concerned about locking pages.  However,
2999 there are two reasons people sometimes are:
3001 @itemize @bullet
3003 @item
3004 Speed.  A page fault is transparent only insofar as the process is not
3005 sensitive to how long it takes to do a simple memory access.  Time-critical
3006 processes, especially realtime processes, may not be able to wait or
3007 may not be able to tolerate variance in execution speed.
3008 @cindex realtime processing
3009 @cindex speed of execution
3011 A process that needs to lock pages for this reason probably also needs
3012 priority among other processes for use of the CPU.  @xref{Priority}.
3014 In some cases, the programmer knows better than the system's demand
3015 paging allocator which pages should remain in real memory to optimize
3016 system performance.  In this case, locking pages can help.
3018 @item
3019 Privacy.  If you keep secrets in virtual memory and that virtual memory
3020 gets paged out, that increases the chance that the secrets will get out.
3021 If a password gets written out to disk swap space, for example, it might
3022 still be there long after virtual and real memory have been wiped clean.
3024 @end itemize
3026 Be aware that when you lock a page, that's one fewer page frame that can
3027 be used to back other virtual memory (by the same or other processes),
3028 which can mean more page faults, which means the system runs more
3029 slowly.  In fact, if you lock enough memory, some programs may not be
3030 able to run at all for lack of real memory.
3032 @node Locked Memory Details
3033 @subsection Locked Memory Details
3035 A memory lock is associated with a virtual page, not a real frame.  The
3036 paging rule is: If a frame backs at least one locked page, don't page it
3037 out.
3039 Memory locks do not stack.  I.e., you can't lock a particular page twice
3040 so that it has to be unlocked twice before it is truly unlocked.  It is
3041 either locked or it isn't.
3043 A memory lock persists until the process that owns the memory explicitly
3044 unlocks it.  (But process termination and exec cause the virtual memory
3045 to cease to exist, which you might say means it isn't locked any more).
3047 Memory locks are not inherited by child processes.  (But note that on a
3048 modern Unix system, immediately after a fork, the parent's and the
3049 child's virtual address space are backed by the same real page frames,
3050 so the child enjoys the parent's locks).  @xref{Creating a Process}.
3052 Because of its ability to impact other processes, only the superuser can
3053 lock a page.  Any process can unlock its own page.
3055 The system sets limits on the amount of memory a process can have locked
3056 and the amount of real memory it can have dedicated to it.  @xref{Limits
3057 on Resources}.
3059 In Linux, locked pages aren't as locked as you might think.
3060 Two virtual pages that are not shared memory can nonetheless be backed
3061 by the same real frame.  The kernel does this in the name of efficiency
3062 when it knows both virtual pages contain identical data, and does it
3063 even if one or both of the virtual pages are locked.
3065 But when a process modifies one of those pages, the kernel must get it a
3066 separate frame and fill it with the page's data.  This is known as a
3067 @dfn{copy-on-write page fault}.  It takes a small amount of time and in
3068 a pathological case, getting that frame may require I/O.
3069 @cindex copy-on-write page fault
3070 @cindex page fault, copy-on-write
3072 To make sure this doesn't happen to your program, don't just lock the
3073 pages.  Write to them as well, unless you know you won't write to them
3074 ever.  And to make sure you have pre-allocated frames for your stack,
3075 enter a scope that declares a C automatic variable larger than the
3076 maximum stack size you will need, set it to something, then return from
3077 its scope.
3079 @node Page Lock Functions
3080 @subsection Functions To Lock And Unlock Pages
3082 The symbols in this section are declared in @file{sys/mman.h}.  These
3083 functions are defined by POSIX.1b, but their availability depends on
3084 your kernel.  If your kernel doesn't allow these functions, they exist
3085 but always fail.  They @emph{are} available with a Linux kernel.
3087 @strong{Portability Note:} POSIX.1b requires that when the @code{mlock}
3088 and @code{munlock} functions are available, the file @file{unistd.h}
3089 define the macro @code{_POSIX_MEMLOCK_RANGE} and the file
3090 @code{limits.h} define the macro @code{PAGESIZE} to be the size of a
3091 memory page in bytes.  It requires that when the @code{mlockall} and
3092 @code{munlockall} functions are available, the @file{unistd.h} file
3093 define the macro @code{_POSIX_MEMLOCK}.  @Theglibc{} conforms to
3094 this requirement.
3096 @comment sys/mman.h
3097 @comment POSIX.1b
3098 @deftypefun int mlock (const void *@var{addr}, size_t @var{len})
3099 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3101 @code{mlock} locks a range of the calling process' virtual pages.
3103 The range of memory starts at address @var{addr} and is @var{len} bytes
3104 long.  Actually, since you must lock whole pages, it is the range of
3105 pages that include any part of the specified range.
3107 When the function returns successfully, each of those pages is backed by
3108 (connected to) a real frame (is resident) and is marked to stay that
3109 way.  This means the function may cause page-ins and have to wait for
3110 them.
3112 When the function fails, it does not affect the lock status of any
3113 pages.
3115 The return value is zero if the function succeeds.  Otherwise, it is
3116 @code{-1} and @code{errno} is set accordingly.  @code{errno} values
3117 specific to this function are:
3119 @table @code
3120 @item ENOMEM
3121 @itemize @bullet
3122 @item
3123 At least some of the specified address range does not exist in the
3124 calling process' virtual address space.
3125 @item
3126 The locking would cause the process to exceed its locked page limit.
3127 @end itemize
3129 @item EPERM
3130 The calling process is not superuser.
3132 @item EINVAL
3133 @var{len} is not positive.
3135 @item ENOSYS
3136 The kernel does not provide @code{mlock} capability.
3138 @end table
3140 You can lock @emph{all} a process' memory with @code{mlockall}.  You
3141 unlock memory with @code{munlock} or @code{munlockall}.
3143 To avoid all page faults in a C program, you have to use
3144 @code{mlockall}, because some of the memory a program uses is hidden
3145 from the C code, e.g. the stack and automatic variables, and you
3146 wouldn't know what address to tell @code{mlock}.
3148 @end deftypefun
3150 @comment sys/mman.h
3151 @comment POSIX.1b
3152 @deftypefun int munlock (const void *@var{addr}, size_t @var{len})
3153 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3155 @code{munlock} unlocks a range of the calling process' virtual pages.
3157 @code{munlock} is the inverse of @code{mlock} and functions completely
3158 analogously to @code{mlock}, except that there is no @code{EPERM}
3159 failure.
3161 @end deftypefun
3163 @comment sys/mman.h
3164 @comment POSIX.1b
3165 @deftypefun int mlockall (int @var{flags})
3166 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3168 @code{mlockall} locks all the pages in a process' virtual memory address
3169 space, and/or any that are added to it in the future.  This includes the
3170 pages of the code, data and stack segment, as well as shared libraries,
3171 user space kernel data, shared memory, and memory mapped files.
3173 @var{flags} is a string of single bit flags represented by the following
3174 macros.  They tell @code{mlockall} which of its functions you want.  All
3175 other bits must be zero.
3177 @table @code
3179 @item MCL_CURRENT
3180 Lock all pages which currently exist in the calling process' virtual
3181 address space.
3183 @item MCL_FUTURE
3184 Set a mode such that any pages added to the process' virtual address
3185 space in the future will be locked from birth.  This mode does not
3186 affect future address spaces owned by the same process so exec, which
3187 replaces a process' address space, wipes out @code{MCL_FUTURE}.
3188 @xref{Executing a File}.
3190 @end table
3192 When the function returns successfully, and you specified
3193 @code{MCL_CURRENT}, all of the process' pages are backed by (connected
3194 to) real frames (they are resident) and are marked to stay that way.
3195 This means the function may cause page-ins and have to wait for them.
3197 When the process is in @code{MCL_FUTURE} mode because it successfully
3198 executed this function and specified @code{MCL_CURRENT}, any system call
3199 by the process that requires space be added to its virtual address space
3200 fails with @code{errno} = @code{ENOMEM} if locking the additional space
3201 would cause the process to exceed its locked page limit.  In the case
3202 that the address space addition that can't be accommodated is stack
3203 expansion, the stack expansion fails and the kernel sends a
3204 @code{SIGSEGV} signal to the process.
3206 When the function fails, it does not affect the lock status of any pages
3207 or the future locking mode.
3209 The return value is zero if the function succeeds.  Otherwise, it is
3210 @code{-1} and @code{errno} is set accordingly.  @code{errno} values
3211 specific to this function are:
3213 @table @code
3214 @item ENOMEM
3215 @itemize @bullet
3216 @item
3217 At least some of the specified address range does not exist in the
3218 calling process' virtual address space.
3219 @item
3220 The locking would cause the process to exceed its locked page limit.
3221 @end itemize
3223 @item EPERM
3224 The calling process is not superuser.
3226 @item EINVAL
3227 Undefined bits in @var{flags} are not zero.
3229 @item ENOSYS
3230 The kernel does not provide @code{mlockall} capability.
3232 @end table
3234 You can lock just specific pages with @code{mlock}.  You unlock pages
3235 with @code{munlockall} and @code{munlock}.
3237 @end deftypefun
3240 @comment sys/mman.h
3241 @comment POSIX.1b
3242 @deftypefun int munlockall (void)
3243 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3245 @code{munlockall} unlocks every page in the calling process' virtual
3246 address space and turns off @code{MCL_FUTURE} 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.  The only way this
3250 function can fail is for generic reasons that all functions and system
3251 calls can fail, so there are no specific @code{errno} values.
3253 @end deftypefun
3258 @ignore
3259 @c This was never actually implemented.  -zw
3260 @node Relocating Allocator
3261 @section Relocating Allocator
3263 @cindex relocating memory allocator
3264 Any system of dynamic memory allocation has overhead: the amount of
3265 space it uses is more than the amount the program asks for.  The
3266 @dfn{relocating memory allocator} achieves very low overhead by moving
3267 blocks in memory as necessary, on its own initiative.
3269 @c @menu
3270 @c * Relocator Concepts::               How to understand relocating allocation.
3271 @c * Using Relocator::          Functions for relocating allocation.
3272 @c @end menu
3274 @node Relocator Concepts
3275 @subsection Concepts of Relocating Allocation
3277 @ifinfo
3278 The @dfn{relocating memory allocator} achieves very low overhead by
3279 moving blocks in memory as necessary, on its own initiative.
3280 @end ifinfo
3282 When you allocate a block with @code{malloc}, the address of the block
3283 never changes unless you use @code{realloc} to change its size.  Thus,
3284 you can safely store the address in various places, temporarily or
3285 permanently, as you like.  This is not safe when you use the relocating
3286 memory allocator, because any and all relocatable blocks can move
3287 whenever you allocate memory in any fashion.  Even calling @code{malloc}
3288 or @code{realloc} can move the relocatable blocks.
3290 @cindex handle
3291 For each relocatable block, you must make a @dfn{handle}---a pointer
3292 object in memory, designated to store the address of that block.  The
3293 relocating allocator knows where each block's handle is, and updates the
3294 address stored there whenever it moves the block, so that the handle
3295 always points to the block.  Each time you access the contents of the
3296 block, you should fetch its address anew from the handle.
3298 To call any of the relocating allocator functions from a signal handler
3299 is almost certainly incorrect, because the signal could happen at any
3300 time and relocate all the blocks.  The only way to make this safe is to
3301 block the signal around any access to the contents of any relocatable
3302 block---not a convenient mode of operation.  @xref{Nonreentrancy}.
3304 @node Using Relocator
3305 @subsection Allocating and Freeing Relocatable Blocks
3307 @pindex malloc.h
3308 In the descriptions below, @var{handleptr} designates the address of the
3309 handle.  All the functions are declared in @file{malloc.h}; all are GNU
3310 extensions.
3312 @comment malloc.h
3313 @comment GNU
3314 @c @deftypefun {void *} r_alloc (void **@var{handleptr}, size_t @var{size})
3315 This function allocates a relocatable block of size @var{size}.  It
3316 stores the block's address in @code{*@var{handleptr}} and returns
3317 a non-null pointer to indicate success.
3319 If @code{r_alloc} can't get the space needed, it stores a null pointer
3320 in @code{*@var{handleptr}}, and returns a null pointer.
3321 @end deftypefun
3323 @comment malloc.h
3324 @comment GNU
3325 @c @deftypefun void r_alloc_free (void **@var{handleptr})
3326 This function is the way to free a relocatable block.  It frees the
3327 block that @code{*@var{handleptr}} points to, and stores a null pointer
3328 in @code{*@var{handleptr}} to show it doesn't point to an allocated
3329 block any more.
3330 @end deftypefun
3332 @comment malloc.h
3333 @comment GNU
3334 @c @deftypefun {void *} r_re_alloc (void **@var{handleptr}, size_t @var{size})
3335 The function @code{r_re_alloc} adjusts the size of the block that
3336 @code{*@var{handleptr}} points to, making it @var{size} bytes long.  It
3337 stores the address of the resized block in @code{*@var{handleptr}} and
3338 returns a non-null pointer to indicate success.
3340 If enough memory is not available, this function returns a null pointer
3341 and does not modify @code{*@var{handleptr}}.
3342 @end deftypefun
3343 @end ignore
3348 @ignore
3349 @comment No longer available...
3351 @comment @node Memory Warnings
3352 @comment @section Memory Usage Warnings
3353 @comment @cindex memory usage warnings
3354 @comment @cindex warnings of memory almost full
3356 @pindex malloc.c
3357 You can ask for warnings as the program approaches running out of memory
3358 space, by calling @code{memory_warnings}.  This tells @code{malloc} to
3359 check memory usage every time it asks for more memory from the operating
3360 system.  This is a GNU extension declared in @file{malloc.h}.
3362 @comment malloc.h
3363 @comment GNU
3364 @comment @deftypefun void memory_warnings (void *@var{start}, void (*@var{warn-func}) (const char *))
3365 Call this function to request warnings for nearing exhaustion of virtual
3366 memory.
3368 The argument @var{start} says where data space begins, in memory.  The
3369 allocator compares this against the last address used and against the
3370 limit of data space, to determine the fraction of available memory in
3371 use.  If you supply zero for @var{start}, then a default value is used
3372 which is right in most circumstances.
3374 For @var{warn-func}, supply a function that @code{malloc} can call to
3375 warn you.  It is called with a string (a warning message) as argument.
3376 Normally it ought to display the string for the user to read.
3377 @end deftypefun
3379 The warnings come when memory becomes 75% full, when it becomes 85%
3380 full, and when it becomes 95% full.  Above 95% you get another warning
3381 each time memory usage increases.
3383 @end ignore