]> git.ipfire.org Git - thirdparty/glibc.git/blame - manual/memory.texi
Add note on MALLOC_MMAP_* environment variables
[thirdparty/glibc.git] / manual / memory.texi
CommitLineData
99a20616
UD
1@node Memory, Character Handling, Error Reporting, Top
2@chapter Virtual Memory Allocation And Paging
3@c %MENU% Allocating virtual memory and controlling paging
28f540f4
RM
4@cindex memory allocation
5@cindex storage allocation
6
99a20616 7This chapter describes how processes manage and use memory in a system
1f77f049 8that uses @theglibc{}.
99a20616 9
1f77f049 10@Theglibc{} has several functions for dynamically allocating
99a20616
UD
11virtual memory in various ways. They vary in generality and in
12efficiency. The library also provides functions for controlling paging
13and allocation of real memory.
14
15
16@menu
17* Memory Concepts:: An introduction to concepts and terminology.
18* Memory Allocation:: Allocating storage for your program data
99a20616 19* Resizing the Data Segment:: @code{brk}, @code{sbrk}
4c23fed5 20* Locking Pages:: Preventing page faults
99a20616
UD
21@end menu
22
23Memory mapped I/O is not discussed in this chapter. @xref{Memory-mapped I/O}.
24
25
26
27@node Memory Concepts
28@section Process Memory Concepts
29
30One of the most basic resources a process has available to it is memory.
31There are a lot of different ways systems organize memory, but in a
32typical one, each process has one linear virtual address space, with
33addresses running from zero to some huge maximum. It need not be
11bf311e 34contiguous; i.e., not all of these addresses actually can be used to
99a20616
UD
35store data.
36
37The virtual memory is divided into pages (4 kilobytes is typical).
38Backing 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
40space might be swap space or just some ordinary disk file. Actually, a
41page of all zeroes sometimes has nothing at all backing it -- there's
42just 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
47
48The same frame of real memory or backing store can back multiple virtual
49pages belonging to multiple processes. This is normally the case, for
1f77f049 50example, with virtual memory occupied by @glibcadj{} code. The same
99a20616
UD
51real memory frame containing the @code{printf} function backs a virtual
52memory page in each of the existing processes that has a @code{printf}
53call in its program.
54
55In order for a program to access any part of a virtual page, the page
56must at that moment be backed by (``connected to'') a real frame. But
57because there is usually a lot more virtual memory than real memory, the
58pages must move back and forth between real memory and backing store
59regularly, coming into real memory when a process needs to access them
60and then retreating to backing store when not needed anymore. This
61movement is called @dfn{paging}.
62
63When a program attempts to access a page which is not at that moment
64backed by real memory, this is known as a @dfn{page fault}. When a page
65fault occurs, the kernel suspends the process, places the page into a
66real page frame (this is called ``paging in'' or ``faulting in''), then
67resumes the process so that from the process' point of view, the page
68was in real memory all along. In fact, to the process, all pages always
69seem to be in real memory. Except for one thing: the elapsed execution
70time of an instruction that would normally be a few nanoseconds is
71suddenly much, much, longer (because the kernel normally has to do I/O
72to complete the page-in). For programs sensitive to that, the functions
73described in @ref{Locking Pages} can control it.
74@cindex page fault
75@cindex paging
76
77Within each virtual address space, a process has to keep track of what
78is at which addresses, and that process is called memory allocation.
79Allocation usually brings to mind meting out scarce resources, but in
80the case of virtual memory, that's not a major goal, because there is
81generally much more of it than anyone needs. Memory allocation within a
68979757 82process is mainly just a matter of making sure that the same byte of
99a20616
UD
83memory isn't used to store two different things.
84
85Processes allocate memory in two major ways: by exec and
86programmatically. Actually, forking is a third way, but it's not very
87interesting. @xref{Creating a Process}.
88
89Exec is the operation of creating a virtual address space for a process,
90loading its basic program into it, and executing the program. It is
91done by the ``exec'' family of functions (e.g. @code{execl}). The
92operation takes a program file (an executable), it allocates space to
93load all the data in the executable, loads it, and transfers control to
94it. That data is most notably the instructions of the program (the
95@dfn{text}), but also literals and constants in the program and even
96some variables: C variables with the static storage class (@pxref{Memory
97Allocation and C}).
98@cindex executable
99@cindex literals
100@cindex constants
101
102Once that program begins to execute, it uses programmatic allocation to
1f77f049 103gain additional memory. In a C program with @theglibc{}, there
99a20616
UD
104are two kinds of programmatic allocation: automatic and dynamic.
105@xref{Memory Allocation and C}.
106
107Memory-mapped I/O is another form of dynamic virtual memory allocation.
108Mapping memory to a file means declaring that the contents of certain
109range of a process' addresses shall be identical to the contents of a
110specified regular file. The system makes the virtual memory initially
111contain the contents of the file, and if you modify the memory, the
112system writes the same modification to the file. Note that due to the
113magic of virtual memory and page faults, there is no reason for the
114system to do I/O to read the file, or allocate real memory for its
115contents, 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
120
121Just as it programmatically allocates memory, the program can
122programmatically deallocate (@dfn{free}) it. You can't free the memory
123that was allocated by exec. When the program exits or execs, you might
124say that all its memory gets freed, but since in both cases the address
125space ceases to exist, the point is really moot. @xref{Program
126Termination}.
127@cindex execing a program
128@cindex freeing memory
129@cindex exiting a program
130
131A process' virtual address space is divided into segments. A segment is
132a contiguous range of virtual addresses. Three important segments are:
28f540f4 133
28f540f4 134@itemize @bullet
28f540f4 135
68979757 136@item
99a20616
UD
137
138The @dfn{text segment} contains a program's instructions and literals and
139static constants. It is allocated by exec and stays the same size for
68979757 140the life of the virtual address space.
28f540f4
RM
141
142@item
99a20616
UD
143The @dfn{data segment} is working storage for the program. It can be
144preallocated and preloaded by exec and the process can extend or shrink
145it by calling functions as described in @xref{Resizing the Data
146Segment}. Its lower end is fixed.
147
68979757 148@item
99a20616
UD
149The @dfn{stack segment} contains a program stack. It grows as the stack
150grows, but doesn't shrink when the stack shrinks.
151
28f540f4 152@end itemize
99a20616
UD
153
154
155
156@node Memory Allocation
68979757 157@section Allocating Storage For Program Data
99a20616
UD
158
159This section covers how ordinary programs manage storage for their data,
160including the famous @code{malloc} function and some fancier facilities
3ef569c7 161special to @theglibc{} and GNU Compiler.
28f540f4
RM
162
163@menu
99a20616 164* Memory Allocation and C:: How to get different kinds of allocation in C.
28f540f4
RM
165* Unconstrained Allocation:: The @code{malloc} facility allows fully general
166 dynamic allocation.
bd355af0 167* Allocation Debugging:: Finding memory leaks and not freed memory.
28f540f4
RM
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.
28f540f4
RM
173@end menu
174
28f540f4 175
99a20616
UD
176@node Memory Allocation and C
177@subsection Memory Allocation in C Programs
28f540f4 178
99a20616
UD
179The C language supports two kinds of memory allocation through the
180variables in C programs:
28f540f4
RM
181
182@itemize @bullet
183@item
184@dfn{Static allocation} is what happens when you declare a static or
185global variable. Each static or global variable defines one block of
186space, of a fixed size. The space is allocated once, when your program
99a20616
UD
187is started (part of the exec operation), and is never freed.
188@cindex static memory allocation
189@cindex static storage class
28f540f4
RM
190
191@item
192@dfn{Automatic allocation} happens when you declare an automatic
193variable, such as a function argument or a local variable. The space
194for an automatic variable is allocated when the compound statement
195containing the declaration is entered, and is freed when that
196compound statement is exited.
99a20616
UD
197@cindex automatic memory allocation
198@cindex automatic storage class
28f540f4 199
99a20616 200In GNU C, the size of the automatic storage can be an expression
28f540f4
RM
201that varies. In other C implementations, it must be a constant.
202@end itemize
203
99a20616 204A third important kind of memory allocation, @dfn{dynamic allocation},
1f77f049 205is not supported by C variables but is available via @glibcadj{}
99a20616
UD
206functions.
207@cindex dynamic memory allocation
208
209@subsubsection Dynamic Memory Allocation
210@cindex dynamic memory allocation
211
212@dfn{Dynamic memory allocation} is a technique in which programs
213determine as they are running where to store some information. You need
214dynamic allocation when the amount of memory you need, or how long you
215continue to need it, depends on factors that are not known before the
216program runs.
217
218For example, you may need a block to store a line read from an input
219file; since there is no limit to how long a line can be, you must
220allocate the memory dynamically and make it dynamically larger as you
221read more of the line.
222
223Or, you may need a block for each record or each definition in the input
224data; since you can't know in advance how many there will be, you must
225allocate a new block for each record or definition as you read it.
226
227When you use dynamic allocation, the allocation of a block of memory is
228an action that the program requests explicitly. You call a function or
229macro when you want to allocate space, and specify the size with an
230argument. If you want to free the space, you do so by calling another
231function or macro. You can do these things whenever you want, as often
232as you want.
233
28f540f4
RM
234Dynamic allocation is not supported by C variables; there is no storage
235class ``dynamic'', and there can never be a C variable whose value is
99a20616 236stored in dynamically allocated space. The only way to get dynamically
1f77f049
JM
237allocated memory is via a system call (which is generally via a @glibcadj{}
238function call), and the only way to refer to dynamically
99a20616
UD
239allocated space is through a pointer. Because it is less convenient,
240and because the actual process of dynamic allocation requires more
241computation time, programmers generally use dynamic allocation only when
242neither static nor automatic allocation will serve.
28f540f4
RM
243
244For 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
246foobar} whose contents are the dynamically allocated space. But you can
247declare a variable of pointer type @code{struct foobar *} and assign it the
248address 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:
250
251@smallexample
252@{
253 struct foobar *ptr
254 = (struct foobar *) malloc (sizeof (struct foobar));
255 ptr->name = x;
256 ptr->next = current_foobar;
257 current_foobar = ptr;
258@}
259@end smallexample
260
261@node Unconstrained Allocation
99a20616
UD
262@subsection Unconstrained Allocation
263@cindex unconstrained memory allocation
28f540f4
RM
264@cindex @code{malloc} function
265@cindex heap, dynamic allocation from
266
267The most general dynamic allocation facility is @code{malloc}. It
268allows you to allocate blocks of memory of any size at any time, make
269them bigger or smaller at any time, and free the blocks individually at
270any time (or never).
271
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.
68979757 283* Aligned Memory Blocks:: Allocating specially aligned memory.
c131718c
UD
284* Malloc Tunable Parameters:: Use @code{mallopt} to adjust allocation
285 parameters.
28f540f4
RM
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
293
294@node Basic Allocation
99a20616 295@subsubsection Basic Memory Allocation
28f540f4
RM
296@cindex allocation of memory with @code{malloc}
297
298To allocate a block of memory, call @code{malloc}. The prototype for
299this function is in @file{stdlib.h}.
300@pindex stdlib.h
301
302@comment malloc.h stdlib.h
f65fd747 303@comment ISO
28f540f4 304@deftypefun {void *} malloc (size_t @var{size})
9f529d7c
AO
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.
321
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?
331
332@c __libc_malloc @asulock @aculock @acsfd @acsmem
333@c force_reg ok
334@c *malloc_hook unguarded
9f529d7c
AO
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]
9f529d7c
AO
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
28f540f4
RM
541This function returns a pointer to a newly allocated block @var{size}
542bytes long, or a null pointer if the block could not be allocated.
543@end deftypefun
544
545The contents of the block are undefined; you must initialize it yourself
546(or use @code{calloc} instead; @pxref{Allocating Cleared Space}).
547Normally you would cast the value as a pointer to the kind of object
548that you want to store in the block. Here we show an example of doing
549so, and of initializing the space with zeros using the library function
0a13c9e9 550@code{memset} (@pxref{Copying Strings and Arrays}):
28f540f4
RM
551
552@smallexample
553struct foo *ptr;
554@dots{}
555ptr = (struct foo *) malloc (sizeof (struct foo));
556if (ptr == 0) abort ();
557memset (ptr, 0, sizeof (struct foo));
558@end smallexample
559
560You can store the result of @code{malloc} into any pointer variable
f65fd747 561without a cast, because @w{ISO C} automatically converts the type
28f540f4
RM
562@code{void *} to another type of pointer when necessary. But the cast
563is necessary in contexts other than assignment operators or if you might
564want your code to run in traditional C.
565
566Remember that when allocating space for a string, the argument to
567@code{malloc} must be one plus the length of the string. This is
568because a string is terminated with a null character that doesn't count
569in the ``length'' of the string but does need space. For example:
570
571@smallexample
572char *ptr;
573@dots{}
574ptr = (char *) malloc (length + 1);
575@end smallexample
576
577@noindent
578@xref{Representation of Strings}, for more information about this.
579
580@node Malloc Examples
99a20616 581@subsubsection Examples of @code{malloc}
28f540f4
RM
582
583If no more space is available, @code{malloc} returns a null pointer.
584You should check the value of @emph{every} call to @code{malloc}. It is
585useful to write a subroutine that calls @code{malloc} and reports an
586error if the value is a null pointer, returning only if the value is
587nonzero. This function is conventionally called @code{xmalloc}. Here
588it is:
589
590@smallexample
591void *
592xmalloc (size_t size)
593@{
e256c421 594 void *value = malloc (size);
28f540f4
RM
595 if (value == 0)
596 fatal ("virtual memory exhausted");
597 return value;
598@}
599@end smallexample
600
601Here is a real example of using @code{malloc} (by way of @code{xmalloc}).
602The function @code{savestring} will copy a sequence of characters into
603a newly allocated null-terminated string:
604
605@smallexample
606@group
607char *
608savestring (const char *ptr, size_t len)
609@{
e256c421 610 char *value = (char *) xmalloc (len + 1);
28f540f4 611 value[len] = '\0';
390955cb 612 return (char *) memcpy (value, ptr, len);
28f540f4
RM
613@}
614@end group
615@end smallexample
616
617The block that @code{malloc} gives you is guaranteed to be aligned so
a7a93d50 618that it can hold any type of data. On @gnusystems{}, the address is
0a096e44 619always a multiple of eight on 32-bit systems, and a multiple of 16 on
c131718c 62064-bit systems. Only rarely is any higher boundary (such as a page
5764c27f
WN
621boundary) necessary; for those cases, use @code{aligned_alloc} or
622@code{posix_memalign} (@pxref{Aligned Memory Blocks}).
28f540f4
RM
623
624Note that the memory located after the end of the block is likely to be
625in use for something else; perhaps a block already allocated by another
626call to @code{malloc}. If you attempt to treat the block as longer than
627you 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
629contents of another block. If you have already allocated a block and
630discover you want it to be bigger, use @code{realloc} (@pxref{Changing
631Block Size}).
632
633@node Freeing after Malloc
99a20616 634@subsubsection Freeing Memory Allocated with @code{malloc}
28f540f4
RM
635@cindex freeing memory allocated with @code{malloc}
636@cindex heap, freeing memory from
637
638When you no longer need a block that you got with @code{malloc}, use the
639function @code{free} to make the block available to be allocated again.
640The prototype for this function is in @file{stdlib.h}.
641@pindex stdlib.h
642
643@comment malloc.h stdlib.h
f65fd747 644@comment ISO
28f540f4 645@deftypefun void free (void *@var{ptr})
9f529d7c
AO
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
99a20616 661The @code{free} function deallocates the block of memory pointed at
28f540f4
RM
662by @var{ptr}.
663@end deftypefun
664
665@comment stdlib.h
666@comment Sun
667@deftypefun void cfree (void *@var{ptr})
9f529d7c
AO
668@safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
669@c alias to free
28f540f4
RM
670This function does the same thing as @code{free}. It's provided for
671backward compatibility with SunOS; you should use @code{free} instead.
672@end deftypefun
673
674Freeing a block alters the contents of the block. @strong{Do not expect to
675find any data (such as a pointer to the next block in a chain of blocks) in
676the block after freeing it.} Copy whatever you need out of the block before
677freeing it! Here is an example of the proper way to free all the blocks in
678a chain, and the strings that they point to:
679
680@smallexample
681struct chain
682 @{
683 struct chain *next;
684 char *name;
685 @}
686
687void
688free_chain (struct chain *chain)
689@{
690 while (chain != 0)
691 @{
692 struct chain *next = chain->next;
693 free (chain->name);
694 free (chain);
695 chain = next;
696 @}
697@}
698@end smallexample
699
700Occasionally, @code{free} can actually return memory to the operating
701system and make the process smaller. Usually, all it can do is allow a
702later call to @code{malloc} to reuse the space. In the meantime, the
703space remains in your program as part of a free-list used internally by
704@code{malloc}.
705
706There is no point in freeing blocks at the end of a program, because all
707of the program's space is given back to the system when the process
708terminates.
709
710@node Changing Block Size
99a20616 711@subsubsection Changing the Size of a Block
28f540f4
RM
712@cindex changing the size of a block (@code{malloc})
713
714Often you do not know for certain how big a block you will ultimately need
715at the time you must begin to use the block. For example, the block might
716be a buffer that you use to hold a line being read from a file; no matter
717how long you make the buffer initially, you may encounter a line that is
718longer.
719
720You can make the block longer by calling @code{realloc}. This function
721is declared in @file{stdlib.h}.
722@pindex stdlib.h
723
724@comment malloc.h stdlib.h
f65fd747 725@comment ISO
28f540f4 726@deftypefun {void *} realloc (void *@var{ptr}, size_t @var{newsize})
9f529d7c
AO
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.
730
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
768
28f540f4
RM
769The @code{realloc} function changes the size of the block whose address is
770@var{ptr} to be @var{newsize}.
771
772Since the space after the end of the block may be in use, @code{realloc}
773may find it necessary to copy the block to a new address where more free
774space is available. The value of @code{realloc} is the new address of the
775block. If the block needs to be moved, @code{realloc} copies the old
776contents.
777
778If you pass a null pointer for @var{ptr}, @code{realloc} behaves just
779like @samp{malloc (@var{newsize})}. This can be convenient, but beware
f65fd747 780that older implementations (before @w{ISO C}) may not support this
28f540f4
RM
781behavior, and will probably crash when @code{realloc} is passed a null
782pointer.
783@end deftypefun
784
785Like @code{malloc}, @code{realloc} may return a null pointer if no
786memory space is available to make the block bigger. When this happens,
787the original block is untouched; it has not been modified or relocated.
788
789In most cases it makes no difference what happens to the original block
790when @code{realloc} fails, because the application program cannot continue
791when it is out of memory, and the only thing to do is to give a fatal error
792message. Often it is convenient to write and use a subroutine,
793conventionally called @code{xrealloc}, that takes care of the error message
794as @code{xmalloc} does for @code{malloc}:
795
796@smallexample
797void *
798xrealloc (void *ptr, size_t size)
799@{
e256c421 800 void *value = realloc (ptr, size);
28f540f4
RM
801 if (value == 0)
802 fatal ("Virtual memory exhausted");
803 return value;
804@}
805@end smallexample
806
807You can also use @code{realloc} to make a block smaller. The reason you
ed277b4e 808would do this is to avoid tying up a lot of memory space when only a little
c131718c
UD
809is 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.
812In several allocation implementations, making a block smaller sometimes
813necessitates copying it, so it can fail if no other space is available.
28f540f4
RM
814
815If the new size you specify is the same as the old size, @code{realloc}
816is guaranteed to change nothing and return the same address that you gave.
817
818@node Allocating Cleared Space
99a20616 819@subsubsection Allocating Cleared Space
28f540f4
RM
820
821The function @code{calloc} allocates memory and clears it to zero. It
822is declared in @file{stdlib.h}.
823@pindex stdlib.h
824
825@comment malloc.h stdlib.h
f65fd747 826@comment ISO
28f540f4 827@deftypefun {void *} calloc (size_t @var{count}, size_t @var{eltsize})
9f529d7c
AO
828@safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
829@c Same caveats as malloc.
830
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
9f529d7c
AO
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
28f540f4
RM
846This function allocates a block long enough to contain a vector of
847@var{count} elements, each of size @var{eltsize}. Its contents are
848cleared to zero before @code{calloc} returns.
849@end deftypefun
850
851You could define @code{calloc} as follows:
852
853@smallexample
854void *
855calloc (size_t count, size_t eltsize)
856@{
857 size_t size = count * eltsize;
858 void *value = malloc (size);
859 if (value != 0)
860 memset (value, 0, size);
861 return value;
862@}
863@end smallexample
864
c131718c
UD
865But 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
868should always define @code{calloc}, too.
869
28f540f4 870@node Efficiency and Malloc
99a20616 871@subsubsection Efficiency Considerations for @code{malloc}
28f540f4
RM
872@cindex efficiency and @code{malloc}
873
99a20616
UD
874
875
876
c131718c
UD
877@ignore
878
879@c No longer true, see below instead.
28f540f4
RM
880To make the best use of @code{malloc}, it helps to know that the GNU
881version of @code{malloc} always dispenses small amounts of memory in
882blocks whose sizes are powers of two. It keeps separate pools for each
883power of two. This holds for sizes up to a page size. Therefore, if
884you 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
887
888Once a page is split up for a particular block size, it can't be reused
889for another size unless all the blocks in it are freed. In many
890programs, this is unlikely to happen. Thus, you can sometimes make a
891program use memory more efficiently by using blocks of the same size for
892many different purposes.
893
894When you ask for memory blocks of a page or larger, @code{malloc} uses a
895different strategy; it rounds the size up to a multiple of a page, and
896it can coalesce and split blocks as needed.
897
898The reason for the two strategies is that it is important to allocate
899and free small blocks as fast as possible, but speed is less important
900for a large block since the program normally spends a fair amount of
901time using it. Also, large blocks are normally fewer in number.
902Therefore, for large blocks, it makes sense to use a method which takes
903more time to minimize the wasted space.
904
c131718c
UD
905@end ignore
906
1f77f049 907As opposed to other versions, the @code{malloc} in @theglibc{}
99a20616
UD
908does not round up block sizes to powers of two, neither for large nor
909for small sizes. Neighboring chunks can be coalesced on a @code{free}
910no matter what their size is. This makes the implementation suitable
911for all kinds of allocation patterns without generally incurring high
912memory waste through fragmentation.
c131718c
UD
913
914Very large blocks (much larger than a page) are allocated with
915@code{mmap} (anonymous or via @code{/dev/zero}) by this implementation.
916This has the great advantage that these chunks are returned to the
917system immediately when they are freed. Therefore, it cannot happen
918that a large chunk becomes ``locked'' in between smaller ones and even
919after 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.
922
28f540f4 923@node Aligned Memory Blocks
99a20616 924@subsubsection Allocating Aligned Memory Blocks
28f540f4
RM
925
926@cindex page boundary
927@cindex alignment (with @code{malloc})
928@pindex stdlib.h
929The address of a block returned by @code{malloc} or @code{realloc} in
a7a93d50 930@gnusystems{} is always a multiple of eight (or sixteen on 64-bit
c131718c 931systems). If you need a block whose address is a multiple of a higher
5764c27f
WN
932power 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}.
935
936@comment stdlib.h
937@deftypefun {void *} aligned_alloc (size_t @var{alignment}, size_t @var{size})
9f529d7c
AO
938@safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
939@c Alias to memalign.
5764c27f
WN
940The @code{aligned_alloc} function allocates a block of @var{size} bytes whose
941address is a multiple of @var{alignment}. The @var{alignment} must be a
942power of two and @var{size} must be a multiple of @var{alignment}.
943
944The @code{aligned_alloc} function returns a null pointer on error and sets
945@code{errno} to one of the following values:
946
947@table @code
948@item ENOMEM
949There was insufficient memory available to satisfy the request.
950
951@item EINVAL
952@var{alignment} is not a power of two.
953
954This function was introduced in @w{ISO C11} and hence may have better
955portability to modern non-POSIX systems than @code{posix_memalign}.
956@end table
957
958@end deftypefun
28f540f4 959
eab0f04c 960@comment malloc.h
28f540f4 961@comment BSD
22a1292a 962@deftypefun {void *} memalign (size_t @var{boundary}, size_t @var{size})
9f529d7c
AO
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.
966
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
28f540f4
RM
986The @code{memalign} function allocates a block of @var{size} bytes whose
987address is a multiple of @var{boundary}. The @var{boundary} must be a
c131718c
UD
988power of two! The function @code{memalign} works by allocating a
989somewhat larger block, and then returning an address within the block
990that is on the specified boundary.
0a096e44
WN
991
992The @code{memalign} function returns a null pointer on error and sets
993@code{errno} to one of the following values:
994
995@table @code
996@item ENOMEM
997There was insufficient memory available to satisfy the request.
998
999@item EINVAL
3ef569c7 1000@var{boundary} is not a power of two.
0a096e44
WN
1001
1002@end table
1003
5764c27f
WN
1004The @code{memalign} function is obsolete and @code{aligned_alloc} or
1005@code{posix_memalign} should be used instead.
28f540f4
RM
1006@end deftypefun
1007
68979757
UD
1008@comment stdlib.h
1009@comment POSIX
1010@deftypefun int posix_memalign (void **@var{memptr}, size_t @var{alignment}, size_t @var{size})
9f529d7c
AO
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).
68979757
UD
1015The @code{posix_memalign} function is similar to the @code{memalign}
1016function in that it returns a buffer of @var{size} bytes aligned to a
1017multiple of @var{alignment}. But it adds one requirement to the
1018parameter @var{alignment}: the value must be a power of two multiple of
1019@code{sizeof (void *)}.
1020
1021If the function succeeds in allocation memory a pointer to the allocated
1022memory is returned in @code{*@var{memptr}} and the return value is zero.
1023Otherwise the function returns an error value indicating the problem.
0a096e44
WN
1024The possible error values returned are:
1025
1026@table @code
1027@item ENOMEM
1028There was insufficient memory available to satisfy the request.
1029
1030@item EINVAL
1031@var{alignment} is not a power of two multiple of @code{sizeof (void *)}.
1032
1033@end table
68979757 1034
cf822e3c 1035This function was introduced in POSIX 1003.1d. Although this function is
5764c27f
WN
1036superseded by @code{aligned_alloc}, it is more portable to older POSIX
1037systems that do not support @w{ISO C11}.
68979757
UD
1038@end deftypefun
1039
28f540f4
RM
1040@comment malloc.h stdlib.h
1041@comment BSD
1042@deftypefun {void *} valloc (size_t @var{size})
9f529d7c
AO
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
9f529d7c
AO
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
28f540f4 1068Using @code{valloc} is like using @code{memalign} and passing the page size
3ef569c7 1069as the value of the first argument. It is implemented like this:
28f540f4
RM
1070
1071@smallexample
1072void *
1073valloc (size_t size)
1074@{
22a1292a 1075 return memalign (getpagesize (), size);
28f540f4
RM
1076@}
1077@end smallexample
b642f101
UD
1078
1079@ref{Query Memory Parameters} for more information about the memory
1080subsystem.
0a096e44 1081
5764c27f
WN
1082The @code{valloc} function is obsolete and @code{aligned_alloc} or
1083@code{posix_memalign} should be used instead.
28f540f4
RM
1084@end deftypefun
1085
c131718c 1086@node Malloc Tunable Parameters
99a20616 1087@subsubsection Malloc Tunable Parameters
c131718c
UD
1088
1089You can adjust some parameters for dynamic memory allocation with the
1090@code{mallopt} function. This function is the general SVID/XPG
1091interface, defined in @file{malloc.h}.
1092@pindex malloc.h
1093
1094@deftypefun int mallopt (int @var{param}, int @var{value})
9f529d7c
AO
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
1102
c131718c
UD
1103When calling @code{mallopt}, the @var{param} argument specifies the
1104parameter to be set, and @var{value} the new value to be set. Possible
1105choices for @var{param}, as defined in @file{malloc.h}, are:
1106
1107@table @code
ec4ff04d
CD
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
1114The maximum number of chunks to allocate with @code{mmap}. Setting this
1115to zero disables all use of @code{mmap}.
2bce3035
SP
1116
1117The default value of this parameter is @code{65536}.
1118
1119This parameter can also be set for the process at startup by setting the
1120environment variable @env{MALLOC_MMAP_MAX_} to the desired value.
1121
c131718c
UD
1122@item M_MMAP_THRESHOLD
1123All chunks larger than this value are allocated outside the normal
1124heap, using the @code{mmap} system call. This way it is guaranteed
1125that the memory for these chunks can be returned to the system on
13c0f771
AJ
1126@code{free}. Note that requests smaller than this threshold might still
1127be allocated via @code{mmap}.
2bce3035
SP
1128
1129If this parameter is not set, the default value is set as 128 KiB and the
1130threshold is adjusted dynamically to suit the allocation patterns of the
1131program. If the parameter is set, the dynamic adjustment is disabled and the
1132value is set statically to the input value.
1133
1134This parameter can also be set for the process at startup by setting the
1135environment variable @env{MALLOC_MMAP_THRESHOLD_} to the desired value.
ec4ff04d 1136@comment TODO: @item M_MXFAST
2bce3035 1137
deb9cabb
AS
1138@item M_PERTURB
1139If non-zero, memory blocks are filled with values depending on some
1140low order bits of this parameter when they are allocated (except when
1141allocated by @code{calloc}) and freed. This can be used to debug the
b741de23
SP
1142use of uninitialized or freed heap memory. Note that this option does not
1143guarantee that the freed block will have any specific values. It only
1144guarantees that the content the block had before it was freed will be
1145overwritten.
2bce3035
SP
1146
1147The default value of this parameter is @code{0}.
1148
1149This parameter can also be set for the process at startup by setting the
1150environment variable @env{MALLOC_MMAP_PERTURB_} to the desired value.
1151
ec4ff04d
CD
1152@item M_TOP_PAD
1153This parameter determines the amount of extra memory to obtain from the
1154system when a call to @code{sbrk} is required. It also specifies the
1155number of bytes to retain when shrinking the heap by calling @code{sbrk}
1156with a negative argument. This provides the necessary hysteresis in
1157heap size such that excessive amounts of system calls can be avoided.
2bce3035
SP
1158
1159The default value of this parameter is @code{0}.
1160
1161This parameter can also be set for the process at startup by setting the
1162environment variable @env{MALLOC_TOP_PAD_} to the desired value.
1163
ec4ff04d
CD
1164@item M_TRIM_THRESHOLD
1165This is the minimum size (in bytes) of the top-most, releasable chunk
1166that will cause @code{sbrk} to be called with a negative argument in
1167order to return memory to the system.
2bce3035
SP
1168
1169If this parameter is not set, the default value is set as 128 KiB and the
1170threshold is adjusted dynamically to suit the allocation patterns of the
1171program. If the parameter is set, the dynamic adjustment is disabled and the
1172value is set statically to the provided input.
1173
1174This parameter can also be set for the process at startup by setting the
1175environment variable @env{MALLOC_TRIM_THRESHOLD_} to the desired value.
1176
c131718c
UD
1177@end table
1178
1179@end deftypefun
1180
28f540f4 1181@node Heap Consistency Checking
99a20616 1182@subsubsection Heap Consistency Checking
28f540f4
RM
1183
1184@cindex heap consistency checking
1185@cindex consistency checking, of heap
1186
99a20616 1187You can ask @code{malloc} to check the consistency of dynamic memory by
28f540f4 1188using the @code{mcheck} function. This function is a GNU extension,
4775243a
UD
1189declared in @file{mcheck.h}.
1190@pindex mcheck.h
28f540f4 1191
4775243a 1192@comment mcheck.h
28f540f4
RM
1193@comment GNU
1194@deftypefun int mcheck (void (*@var{abortfn}) (enum mcheck_status @var{status}))
9f529d7c
AO
1195@safety{@prelim{}@mtunsafe{@mtasurace{:mcheck} @mtasuconst{:malloc_hooks}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
1196@c The hooks must be set up before malloc is first used, which sort of
1197@c implies @mtuinit/@asuinit but since the function is a no-op if malloc
1198@c was already used, that doesn't pose any safety issues. The actual
1199@c problem is with the hooks, designed for single-threaded
1200@c fully-synchronous operation: they manage an unguarded linked list of
1201@c allocated blocks, and get temporarily overwritten before calling the
1202@c allocation functions recursively while holding the old hooks. There
1203@c are no guards for thread safety, and inconsistent hooks may be found
1204@c within signal handlers or left behind in case of cancellation.
1205
28f540f4
RM
1206Calling @code{mcheck} tells @code{malloc} to perform occasional
1207consistency checks. These will catch things such as writing
1208past the end of a block that was allocated with @code{malloc}.
1209
1210The @var{abortfn} argument is the function to call when an inconsistency
1211is found. If you supply a null pointer, then @code{mcheck} uses a
1212default function which prints a message and calls @code{abort}
1213(@pxref{Aborting a Program}). The function you supply is called with
1214one argument, which says what sort of inconsistency was detected; its
1215type is described below.
1216
1217It is too late to begin allocation checking once you have allocated
1218anything with @code{malloc}. So @code{mcheck} does nothing in that
1219case. The function returns @code{-1} if you call it too late, and
1220@code{0} otherwise (when it is successful).
1221
1222The easiest way to arrange to call @code{mcheck} early enough is to use
1223the option @samp{-lmcheck} when you link your program; then you don't
bc938d3d 1224need to modify your program source at all. Alternatively you might use
3cb07217
UD
1225a debugger to insert a call to @code{mcheck} whenever the program is
1226started, for example these gdb commands will automatically call @code{mcheck}
1227whenever the program starts:
1228
1229@smallexample
1230(gdb) break main
1231Breakpoint 1, main (argc=2, argv=0xbffff964) at whatever.c:10
1232(gdb) command 1
1233Type commands for when breakpoint 1 is hit, one per line.
1234End with a line saying just "end".
1235>call mcheck(0)
1236>continue
1237>end
95fdc6a0 1238(gdb) @dots{}
3cb07217
UD
1239@end smallexample
1240
1241This will however only work if no initialization function of any object
1242involved calls any of the @code{malloc} functions since @code{mcheck}
1243must be called before the first such function.
1244
28f540f4
RM
1245@end deftypefun
1246
1247@deftypefun {enum mcheck_status} mprobe (void *@var{pointer})
9f529d7c
AO
1248@safety{@prelim{}@mtunsafe{@mtasurace{:mcheck} @mtasuconst{:malloc_hooks}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
1249@c The linked list of headers may be modified concurrently by other
1250@c threads, and it may find a partial update if called from a signal
1251@c handler. It's mostly read only, so cancelling it might be safe, but
1252@c it will modify global state that, if cancellation hits at just the
1253@c right spot, may be left behind inconsistent. This path is only taken
1254@c if checkhdr finds an inconsistency. If the inconsistency could only
1255@c occur because of earlier undefined behavior, that wouldn't be an
1256@c additional safety issue problem, but because of the other concurrency
1257@c issues in the mcheck hooks, the apparent inconsistency could be the
1258@c result of mcheck's own internal data race. So, AC-Unsafe it is.
1259
28f540f4
RM
1260The @code{mprobe} function lets you explicitly check for inconsistencies
1261in a particular allocated block. You must have already called
1262@code{mcheck} at the beginning of the program, to do its occasional
1263checks; calling @code{mprobe} requests an additional consistency check
1264to be done at the time of the call.
1265
1266The argument @var{pointer} must be a pointer returned by @code{malloc}
1267or @code{realloc}. @code{mprobe} returns a value that says what
1268inconsistency, if any, was found. The values are described below.
1269@end deftypefun
1270
1271@deftp {Data Type} {enum mcheck_status}
1272This enumerated type describes what kind of inconsistency was detected
1273in an allocated block, if any. Here are the possible values:
1274
1275@table @code
1276@item MCHECK_DISABLED
1277@code{mcheck} was not called before the first allocation.
1278No consistency checking can be done.
1279@item MCHECK_OK
1280No inconsistency detected.
1281@item MCHECK_HEAD
1282The data immediately before the block was modified.
1283This commonly happens when an array index or pointer
1284is decremented too far.
1285@item MCHECK_TAIL
1286The data immediately after the block was modified.
1287This commonly happens when an array index or pointer
1288is incremented too far.
1289@item MCHECK_FREE
1290The block was already freed.
1291@end table
1292@end deftp
1293
7551a1e5
UD
1294Another possibility to check for and guard against bugs in the use of
1295@code{malloc}, @code{realloc} and @code{free} is to set the environment
1296variable @code{MALLOC_CHECK_}. When @code{MALLOC_CHECK_} is set, a
1297special (less efficient) implementation is used which is designed to be
1298tolerant against simple errors, such as double calls of @code{free} with
1299the same argument, or overruns of a single byte (off-by-one bugs). Not
bc938d3d 1300all such errors can be protected against, however, and memory leaks can
7551a1e5
UD
1301result. If @code{MALLOC_CHECK_} is set to @code{0}, any detected heap
1302corruption is silently ignored; if set to @code{1}, a diagnostic is
1303printed on @code{stderr}; if set to @code{2}, @code{abort} is called
1304immediately. This can be useful because otherwise a crash may happen
1305much later, and the true cause for the problem is then very hard to
1306track down.
1307
68979757
UD
1308There is one problem with @code{MALLOC_CHECK_}: in SUID or SGID binaries
1309it could possibly be exploited since diverging from the normal programs
0bc93a2f 1310behavior it now writes something to the standard error descriptor.
68979757
UD
1311Therefore the use of @code{MALLOC_CHECK_} is disabled by default for
1312SUID and SGID binaries. It can be enabled again by the system
1313administrator by adding a file @file{/etc/suid-debug} (the content is
1314not important it could be empty).
1315
789b13c4 1316So, what's the difference between using @code{MALLOC_CHECK_} and linking
bc938d3d 1317with @samp{-lmcheck}? @code{MALLOC_CHECK_} is orthogonal with respect to
789b13c4
UD
1318@samp{-lmcheck}. @samp{-lmcheck} has been added for backward
1319compatibility. Both @code{MALLOC_CHECK_} and @samp{-lmcheck} should
1320uncover the same bugs - but using @code{MALLOC_CHECK_} you don't need to
1321recompile your application.
1322
28f540f4 1323@node Hooks for Malloc
99a20616 1324@subsubsection Memory Allocation Hooks
28f540f4
RM
1325@cindex allocation hooks, for @code{malloc}
1326
1f77f049 1327@Theglibc{} lets you modify the behavior of @code{malloc},
28f540f4
RM
1328@code{realloc}, and @code{free} by specifying appropriate hook
1329functions. You can use these hooks to help you debug programs that use
99a20616 1330dynamic memory allocation, for example.
28f540f4
RM
1331
1332The hook variables are declared in @file{malloc.h}.
1333@pindex malloc.h
1334
1335@comment malloc.h
1336@comment GNU
1337@defvar __malloc_hook
bc938d3d
UD
1338The value of this variable is a pointer to the function that
1339@code{malloc} uses whenever it is called. You should define this
1340function to look like @code{malloc}; that is, like:
28f540f4
RM
1341
1342@smallexample
18a3a9a3 1343void *@var{function} (size_t @var{size}, const void *@var{caller})
28f540f4 1344@end smallexample
bd355af0
UD
1345
1346The value of @var{caller} is the return address found on the stack when
bc938d3d
UD
1347the @code{malloc} function was called. This value allows you to trace
1348the memory consumption of the program.
28f540f4
RM
1349@end defvar
1350
1351@comment malloc.h
1352@comment GNU
1353@defvar __realloc_hook
1354The value of this variable is a pointer to function that @code{realloc}
1355uses whenever it is called. You should define this function to look
1356like @code{realloc}; that is, like:
1357
1358@smallexample
18a3a9a3 1359void *@var{function} (void *@var{ptr}, size_t @var{size}, const void *@var{caller})
28f540f4 1360@end smallexample
bd355af0
UD
1361
1362The value of @var{caller} is the return address found on the stack when
e8b1163e 1363the @code{realloc} function was called. This value allows you to trace the
bd355af0 1364memory consumption of the program.
28f540f4
RM
1365@end defvar
1366
1367@comment malloc.h
1368@comment GNU
1369@defvar __free_hook
1370The value of this variable is a pointer to function that @code{free}
1371uses whenever it is called. You should define this function to look
1372like @code{free}; that is, like:
1373
1374@smallexample
18a3a9a3 1375void @var{function} (void *@var{ptr}, const void *@var{caller})
28f540f4 1376@end smallexample
bd355af0
UD
1377
1378The value of @var{caller} is the return address found on the stack when
e8b1163e 1379the @code{free} function was called. This value allows you to trace the
bd355af0 1380memory consumption of the program.
28f540f4
RM
1381@end defvar
1382
3cb07217
UD
1383@comment malloc.h
1384@comment GNU
1385@defvar __memalign_hook
5764c27f
WN
1386The value of this variable is a pointer to function that @code{aligned_alloc},
1387@code{memalign}, @code{posix_memalign} and @code{valloc} use whenever they
cf822e3c 1388are called. You should define this function to look like @code{aligned_alloc};
5764c27f 1389that is, like:
3cb07217
UD
1390
1391@smallexample
46ca7a1c 1392void *@var{function} (size_t @var{alignment}, size_t @var{size}, const void *@var{caller})
3cb07217 1393@end smallexample
18a3a9a3
UD
1394
1395The value of @var{caller} is the return address found on the stack when
5764c27f
WN
1396the @code{aligned_alloc}, @code{memalign}, @code{posix_memalign} or
1397@code{valloc} functions are called. This value allows you to trace the
1398memory consumption of the program.
3cb07217
UD
1399@end defvar
1400
28f540f4
RM
1401You must make sure that the function you install as a hook for one of
1402these functions does not call that function recursively without restoring
1403the old value of the hook first! Otherwise, your program will get stuck
3cb07217
UD
1404in an infinite recursion. Before calling the function recursively, one
1405should make sure to restore all the hooks to their previous value. When
1406coming back from the recursive call, all the hooks should be resaved
1407since a hook might modify itself.
28f540f4 1408
b2f46c3c
UD
1409An issue to look out for is the time at which the malloc hook functions
1410can be safely installed. If the hook functions call the malloc-related
1411functions recursively, it is necessary that malloc has already properly
1412initialized itself at the time when @code{__malloc_hook} etc. is
1413assigned to. On the other hand, if the hook functions provide a
1414complete malloc implementation of their own, it is vital that the hooks
1415are assigned to @emph{before} the very first @code{malloc} call has
1416completed, because otherwise a chunk obtained from the ordinary,
1417un-hooked malloc may later be handed to @code{__free_hook}, for example.
1418
3cb07217
UD
1419Here is an example showing how to use @code{__malloc_hook} and
1420@code{__free_hook} properly. It installs a function that prints out
1421information every time @code{malloc} or @code{free} is called. We just
1422assume here that @code{realloc} and @code{memalign} are not used in our
1423program.
28f540f4
RM
1424
1425@smallexample
18a3a9a3
UD
1426/* Prototypes for __malloc_hook, __free_hook */
1427#include <malloc.h>
3cb07217
UD
1428
1429/* Prototypes for our hooks. */
2ac057a0 1430static void my_init_hook (void);
18a3a9a3
UD
1431static void *my_malloc_hook (size_t, const void *);
1432static void my_free_hook (void*, const void *);
b2f46c3c 1433
b2f46c3c 1434static void
2ba3cfa1 1435my_init (void)
b2f46c3c
UD
1436@{
1437 old_malloc_hook = __malloc_hook;
1438 old_free_hook = __free_hook;
1439 __malloc_hook = my_malloc_hook;
1440 __free_hook = my_free_hook;
1441@}
3cb07217 1442
28f540f4 1443static void *
18a3a9a3 1444my_malloc_hook (size_t size, const void *caller)
28f540f4
RM
1445@{
1446 void *result;
3cb07217 1447 /* Restore all old hooks */
28f540f4 1448 __malloc_hook = old_malloc_hook;
3cb07217
UD
1449 __free_hook = old_free_hook;
1450 /* Call recursively */
28f540f4 1451 result = malloc (size);
0bc93a2f 1452 /* Save underlying hooks */
3cb07217
UD
1453 old_malloc_hook = __malloc_hook;
1454 old_free_hook = __free_hook;
28f540f4
RM
1455 /* @r{@code{printf} might call @code{malloc}, so protect it too.} */
1456 printf ("malloc (%u) returns %p\n", (unsigned int) size, result);
3cb07217 1457 /* Restore our own hooks */
28f540f4 1458 __malloc_hook = my_malloc_hook;
3cb07217 1459 __free_hook = my_free_hook;
28f540f4
RM
1460 return result;
1461@}
1462
2ac057a0 1463static void
18a3a9a3 1464my_free_hook (void *ptr, const void *caller)
3cb07217
UD
1465@{
1466 /* Restore all old hooks */
1467 __malloc_hook = old_malloc_hook;
1468 __free_hook = old_free_hook;
1469 /* Call recursively */
1470 free (ptr);
0bc93a2f 1471 /* Save underlying hooks */
3cb07217
UD
1472 old_malloc_hook = __malloc_hook;
1473 old_free_hook = __free_hook;
1474 /* @r{@code{printf} might call @code{free}, so protect it too.} */
1475 printf ("freed pointer %p\n", ptr);
1476 /* Restore our own hooks */
1477 __malloc_hook = my_malloc_hook;
1478 __free_hook = my_free_hook;
1479@}
1480
28f540f4
RM
1481main ()
1482@{
2ba3cfa1 1483 my_init ();
95fdc6a0 1484 @dots{}
28f540f4
RM
1485@}
1486@end smallexample
1487
1488The @code{mcheck} function (@pxref{Heap Consistency Checking}) works by
1489installing such hooks.
1490
1491@c __morecore, __after_morecore_hook are undocumented
1492@c It's not clear whether to document them.
1493
1494@node Statistics of Malloc
99a20616 1495@subsubsection Statistics for Memory Allocation with @code{malloc}
28f540f4
RM
1496
1497@cindex allocation statistics
99a20616 1498You can get information about dynamic memory allocation by calling the
c131718c
UD
1499@code{mallinfo} function. This function and its associated data type
1500are declared in @file{malloc.h}; they are an extension of the standard
1501SVID/XPG version.
28f540f4
RM
1502@pindex malloc.h
1503
1504@comment malloc.h
1505@comment GNU
c131718c 1506@deftp {Data Type} {struct mallinfo}
28f540f4 1507This structure type is used to return information about the dynamic
99a20616 1508memory allocator. It contains the following members:
28f540f4
RM
1509
1510@table @code
c131718c
UD
1511@item int arena
1512This is the total size of memory allocated with @code{sbrk} by
1513@code{malloc}, in bytes.
1514
1515@item int ordblks
99a20616 1516This is the number of chunks not in use. (The memory allocator
c131718c
UD
1517internally gets chunks of memory from the operating system, and then
1518carves them up to satisfy individual @code{malloc} requests; see
1519@ref{Efficiency and Malloc}.)
1520
1521@item int smblks
1522This field is unused.
1523
1524@item int hblks
1525This is the total number of chunks allocated with @code{mmap}.
1526
1527@item int hblkhd
1528This is the total size of memory allocated with @code{mmap}, in bytes.
1529
1530@item int usmblks
ca135f82 1531This field is unused and always 0.
28f540f4 1532
c131718c
UD
1533@item int fsmblks
1534This field is unused.
28f540f4 1535
c131718c
UD
1536@item int uordblks
1537This is the total size of memory occupied by chunks handed out by
1538@code{malloc}.
1539
1540@item int fordblks
1541This is the total size of memory occupied by free (not in use) chunks.
28f540f4 1542
c131718c 1543@item int keepcost
e8b1163e 1544This is the size of the top-most releasable chunk that normally
11bf311e 1545borders the end of the heap (i.e., the high end of the virtual address
99a20616 1546space's data segment).
28f540f4 1547
28f540f4
RM
1548@end table
1549@end deftp
1550
1551@comment malloc.h
c131718c
UD
1552@comment SVID
1553@deftypefun {struct mallinfo} mallinfo (void)
9f529d7c
AO
1554@safety{@prelim{}@mtunsafe{@mtuinit{} @mtasuconst{:mallopt}}@asunsafe{@asuinit{} @asulock{}}@acunsafe{@acuinit{} @aculock{}}}
1555@c Accessing mp_.n_mmaps and mp_.max_mmapped_mem, modified with atomics
1556@c but non-atomically elsewhere, may get us inconsistent results. We
1557@c mark the statistics as unsafe, rather than the fast-path functions
1558@c that collect the possibly inconsistent data.
1559
1560@c __libc_mallinfo @mtuinit @mtasuconst:mallopt @asuinit @asulock @aculock
1561@c ptmalloc_init (once) dup @mtsenv @asulock @aculock @acsfd @acsmem
1562@c mutex_lock dup @asulock @aculock
1563@c int_mallinfo @mtasuconst:mallopt [mp_ access on main_arena]
1564@c malloc_consolidate dup ok
1565@c check_malloc_state dup ok/disabled
1566@c chunksize dup ok
1567@c fastbin dupo ok
1568@c bin_at dup ok
1569@c last dup ok
1570@c mutex_unlock @aculock
1571
28f540f4 1572This function returns information about the current dynamic memory usage
c131718c 1573in a structure of type @code{struct mallinfo}.
28f540f4
RM
1574@end deftypefun
1575
1576@node Summary of Malloc
99a20616 1577@subsubsection Summary of @code{malloc}-Related Functions
28f540f4
RM
1578
1579Here is a summary of the functions that work with @code{malloc}:
1580
1581@table @code
1582@item void *malloc (size_t @var{size})
1583Allocate a block of @var{size} bytes. @xref{Basic Allocation}.
1584
1585@item void free (void *@var{addr})
1586Free a block previously allocated by @code{malloc}. @xref{Freeing after
1587Malloc}.
1588
1589@item void *realloc (void *@var{addr}, size_t @var{size})
1590Make a block previously allocated by @code{malloc} larger or smaller,
1591possibly by copying it to a new location. @xref{Changing Block Size}.
1592
1593@item void *calloc (size_t @var{count}, size_t @var{eltsize})
1594Allocate a block of @var{count} * @var{eltsize} bytes using
1595@code{malloc}, and set its contents to zero. @xref{Allocating Cleared
1596Space}.
1597
1598@item void *valloc (size_t @var{size})
1599Allocate a block of @var{size} bytes, starting on a page boundary.
1600@xref{Aligned Memory Blocks}.
1601
5764c27f
WN
1602@item void *aligned_alloc (size_t @var{size}, size_t @var{alignment})
1603Allocate a block of @var{size} bytes, starting on an address that is a
1604multiple of @var{alignment}. @xref{Aligned Memory Blocks}.
1605
0a096e44
WN
1606@item int posix_memalign (void **@var{memptr}, size_t @var{alignment}, size_t @var{size})
1607Allocate a block of @var{size} bytes, starting on an address that is a
1608multiple of @var{alignment}. @xref{Aligned Memory Blocks}.
1609
28f540f4
RM
1610@item void *memalign (size_t @var{size}, size_t @var{boundary})
1611Allocate a block of @var{size} bytes, starting on an address that is a
1612multiple of @var{boundary}. @xref{Aligned Memory Blocks}.
1613
c131718c 1614@item int mallopt (int @var{param}, int @var{value})
8b7fb588 1615Adjust a tunable parameter. @xref{Malloc Tunable Parameters}.
c131718c 1616
28f540f4
RM
1617@item int mcheck (void (*@var{abortfn}) (void))
1618Tell @code{malloc} to perform occasional consistency checks on
1619dynamically allocated memory, and to call @var{abortfn} when an
1620inconsistency is found. @xref{Heap Consistency Checking}.
1621
18a3a9a3 1622@item void *(*__malloc_hook) (size_t @var{size}, const void *@var{caller})
28f540f4
RM
1623A pointer to a function that @code{malloc} uses whenever it is called.
1624
18a3a9a3 1625@item void *(*__realloc_hook) (void *@var{ptr}, size_t @var{size}, const void *@var{caller})
28f540f4
RM
1626A pointer to a function that @code{realloc} uses whenever it is called.
1627
18a3a9a3 1628@item void (*__free_hook) (void *@var{ptr}, const void *@var{caller})
28f540f4
RM
1629A pointer to a function that @code{free} uses whenever it is called.
1630
18a3a9a3 1631@item void (*__memalign_hook) (size_t @var{size}, size_t @var{alignment}, const void *@var{caller})
5764c27f
WN
1632A pointer to a function that @code{aligned_alloc}, @code{memalign},
1633@code{posix_memalign} and @code{valloc} use whenever they are called.
3cb07217 1634
c131718c 1635@item struct mallinfo mallinfo (void)
28f540f4
RM
1636Return information about the current dynamic memory usage.
1637@xref{Statistics of Malloc}.
1638@end table
1639
bd355af0 1640@node Allocation Debugging
99a20616 1641@subsection Allocation Debugging
bd355af0
UD
1642@cindex allocation debugging
1643@cindex malloc debugger
1644
bc938d3d 1645A complicated task when programming with languages which do not use
bd355af0 1646garbage collected dynamic memory allocation is to find memory leaks.
3ef569c7 1647Long running programs must ensure that dynamically allocated objects are
bd355af0
UD
1648freed at the end of their lifetime. If this does not happen the system
1649runs out of memory, sooner or later.
1650
1f77f049 1651The @code{malloc} implementation in @theglibc{} provides some
bc938d3d 1652simple means to detect such leaks and obtain some information to find
bd355af0
UD
1653the location. To do this the application must be started in a special
1654mode which is enabled by an environment variable. There are no speed
bc938d3d 1655penalties for the program if the debugging mode is not enabled.
bd355af0
UD
1656
1657@menu
1658* Tracing malloc:: How to install the tracing functionality.
1659* Using the Memory Debugger:: Example programs excerpts.
1660* Tips for the Memory Debugger:: Some more or less clever ideas.
1661* Interpreting the traces:: What do all these lines mean?
1662@end menu
1663
1664@node Tracing malloc
99a20616 1665@subsubsection How to install the tracing functionality
bd355af0
UD
1666
1667@comment mcheck.h
1668@comment GNU
1669@deftypefun void mtrace (void)
9f529d7c
AO
1670@safety{@prelim{}@mtunsafe{@mtsenv{} @mtasurace{:mtrace} @mtasuconst{:malloc_hooks} @mtuinit{}}@asunsafe{@asuinit{} @ascuheap{} @asucorrupt{} @asulock{}}@acunsafe{@acuinit{} @acucorrupt{} @aculock{} @acsfd{} @acsmem{}}}
1671@c Like the mcheck hooks, these are not designed with thread safety in
1672@c mind, because the hook pointers are temporarily modified without
1673@c regard to other threads, signals or cancellation.
1674
1675@c mtrace @mtuinit @mtasurace:mtrace @mtsenv @asuinit @ascuheap @asucorrupt @acuinit @acucorrupt @aculock @acsfd @acsmem
1676@c __libc_secure_getenv dup @mtsenv
1677@c malloc dup @ascuheap @acsmem
1678@c fopen dup @ascuheap @asulock @aculock @acsmem @acsfd
1679@c fcntl dup ok
1680@c setvbuf dup @aculock
1681@c fprintf dup (on newly-created stream) @aculock
1682@c __cxa_atexit (once) dup @asulock @aculock @acsmem
1683@c free dup @ascuheap @acsmem
bd355af0
UD
1684When the @code{mtrace} function is called it looks for an environment
1685variable named @code{MALLOC_TRACE}. This variable is supposed to
1686contain a valid file name. The user must have write access. If the
1687file already exists it is truncated. If the environment variable is not
1688set or it does not name a valid file which can be opened for writing
0bc93a2f 1689nothing is done. The behavior of @code{malloc} etc. is not changed.
bc938d3d
UD
1690For obvious reasons this also happens if the application is installed
1691with the SUID or SGID bit set.
bd355af0 1692
e8b1163e 1693If the named file is successfully opened, @code{mtrace} installs special
bd355af0 1694handlers for the functions @code{malloc}, @code{realloc}, and
e8b1163e 1695@code{free} (@pxref{Hooks for Malloc}). From then on, all uses of these
bd355af0 1696functions are traced and protocolled into the file. There is now of
bc938d3d 1697course a speed penalty for all calls to the traced functions so tracing
e8b1163e 1698should not be enabled during normal use.
bd355af0
UD
1699
1700This function is a GNU extension and generally not available on other
1701systems. The prototype can be found in @file{mcheck.h}.
1702@end deftypefun
1703
1704@comment mcheck.h
1705@comment GNU
1706@deftypefun void muntrace (void)
9f529d7c
AO
1707@safety{@prelim{}@mtunsafe{@mtasurace{:mtrace} @mtasuconst{:malloc_hooks} @mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acucorrupt{} @acsmem{} @aculock{} @acsfd{}}}
1708
1709@c muntrace @mtasurace:mtrace @mtslocale @asucorrupt @ascuheap @acucorrupt @acsmem @aculock @acsfd
1710@c fprintf (fputs) dup @mtslocale @asucorrupt @ascuheap @acsmem @aculock @acucorrupt
1711@c fclose dup @ascuheap @asulock @aculock @acsmem @acsfd
bd355af0 1712The @code{muntrace} function can be called after @code{mtrace} was used
0bc93a2f 1713to enable tracing the @code{malloc} calls. If no (successful) call of
bd355af0
UD
1714@code{mtrace} was made @code{muntrace} does nothing.
1715
1716Otherwise it deinstalls the handlers for @code{malloc}, @code{realloc},
1717and @code{free} and then closes the protocol file. No calls are
bc938d3d 1718protocolled anymore and the program runs again at full speed.
bd355af0
UD
1719
1720This function is a GNU extension and generally not available on other
1721systems. The prototype can be found in @file{mcheck.h}.
1722@end deftypefun
1723
1724@node Using the Memory Debugger
99a20616 1725@subsubsection Example program excerpts
bd355af0
UD
1726
1727Even though the tracing functionality does not influence the runtime
0bc93a2f 1728behavior of the program it is not a good idea to call @code{mtrace} in
bc938d3d
UD
1729all programs. Just imagine that you debug a program using @code{mtrace}
1730and all other programs used in the debugging session also trace their
1731@code{malloc} calls. The output file would be the same for all programs
1732and thus is unusable. Therefore one should call @code{mtrace} only if
1733compiled for debugging. A program could therefore start like this:
bd355af0
UD
1734
1735@example
1736#include <mcheck.h>
1737
1738int
1739main (int argc, char *argv[])
1740@{
1741#ifdef DEBUGGING
1742 mtrace ();
1743#endif
1744 @dots{}
1745@}
1746@end example
1747
3ef569c7 1748This is all that is needed if you want to trace the calls during the
bd355af0
UD
1749whole runtime of the program. Alternatively you can stop the tracing at
1750any time with a call to @code{muntrace}. It is even possible to restart
bc938d3d
UD
1751the tracing again with a new call to @code{mtrace}. But this can cause
1752unreliable results since there may be calls of the functions which are
1753not called. Please note that not only the application uses the traced
1754functions, also libraries (including the C library itself) use these
1755functions.
bd355af0 1756
3ef569c7
RJ
1757This last point is also why it is not a good idea to call @code{muntrace}
1758before the program terminates. The libraries are informed about the
bd355af0
UD
1759termination of the program only after the program returns from
1760@code{main} or calls @code{exit} and so cannot free the memory they use
1761before this time.
1762
1763So the best thing one can do is to call @code{mtrace} as the very first
1764function in the program and never call @code{muntrace}. So the program
1765traces almost all uses of the @code{malloc} functions (except those
1766calls which are executed by constructors of the program or used
1767libraries).
1768
1769@node Tips for the Memory Debugger
99a20616 1770@subsubsection Some more or less clever ideas
bd355af0
UD
1771
1772You know the situation. The program is prepared for debugging and in
1773all debugging sessions it runs well. But once it is started without
bc938d3d
UD
1774debugging the error shows up. A typical example is a memory leak that
1775becomes visible only when we turn off the debugging. If you foresee
1776such situations you can still win. Simply use something equivalent to
1777the following little program:
bd355af0
UD
1778
1779@example
1780#include <mcheck.h>
1781#include <signal.h>
1782
1783static void
1784enable (int sig)
1785@{
1786 mtrace ();
1787 signal (SIGUSR1, enable);
1788@}
1789
1790static void
1791disable (int sig)
1792@{
1793 muntrace ();
1794 signal (SIGUSR2, disable);
1795@}
1796
1797int
1798main (int argc, char *argv[])
1799@{
1800 @dots{}
1801
1802 signal (SIGUSR1, enable);
1803 signal (SIGUSR2, disable);
1804
1805 @dots{}
1806@}
1807@end example
1808
9756dfe1 1809I.e., the user can start the memory debugger any time s/he wants if the
bd355af0
UD
1810program was started with @code{MALLOC_TRACE} set in the environment.
1811The output will of course not show the allocations which happened before
1812the first signal but if there is a memory leak this will show up
1813nevertheless.
1814
1815@node Interpreting the traces
99a20616 1816@subsubsection Interpreting the traces
bd355af0
UD
1817
1818If you take a look at the output it will look similar to this:
1819
1820@example
1821= Start
1822@ [0x8048209] - 0x8064cc8
1823@ [0x8048209] - 0x8064ce0
1824@ [0x8048209] - 0x8064cf8
1825@ [0x80481eb] + 0x8064c48 0x14
1826@ [0x80481eb] + 0x8064c60 0x14
1827@ [0x80481eb] + 0x8064c78 0x14
1828@ [0x80481eb] + 0x8064c90 0x14
1829= End
1830@end example
1831
1832What this all means is not really important since the trace file is not
bc938d3d 1833meant to be read by a human. Therefore no attention is given to
1f77f049
JM
1834readability. Instead there is a program which comes with @theglibc{}
1835which interprets the traces and outputs a summary in an
bd355af0
UD
1836user-friendly way. The program is called @code{mtrace} (it is in fact a
1837Perl script) and it takes one or two arguments. In any case the name of
bc938d3d
UD
1838the file with the trace output must be specified. If an optional
1839argument precedes the name of the trace file this must be the name of
1840the program which generated the trace.
bd355af0
UD
1841
1842@example
1843drepper$ mtrace tst-mtrace log
1844No memory leaks.
1845@end example
1846
1847In this case the program @code{tst-mtrace} was run and it produced a
1848trace file @file{log}. The message printed by @code{mtrace} shows there
1849are no problems with the code, all allocated memory was freed
1850afterwards.
1851
1852If we call @code{mtrace} on the example trace given above we would get a
1853different outout:
1854
1855@example
1856drepper$ mtrace errlog
1857- 0x08064cc8 Free 2 was never alloc'd 0x8048209
1858- 0x08064ce0 Free 3 was never alloc'd 0x8048209
1859- 0x08064cf8 Free 4 was never alloc'd 0x8048209
1860
1861Memory not freed:
1862-----------------
1863 Address Size Caller
18640x08064c48 0x14 at 0x80481eb
18650x08064c60 0x14 at 0x80481eb
18660x08064c78 0x14 at 0x80481eb
18670x08064c90 0x14 at 0x80481eb
1868@end example
1869
1870We have called @code{mtrace} with only one argument and so the script
1871has no chance to find out what is meant with the addresses given in the
1872trace. We can do better:
1873
1874@example
bc938d3d
UD
1875drepper$ mtrace tst errlog
1876- 0x08064cc8 Free 2 was never alloc'd /home/drepper/tst.c:39
1877- 0x08064ce0 Free 3 was never alloc'd /home/drepper/tst.c:39
1878- 0x08064cf8 Free 4 was never alloc'd /home/drepper/tst.c:39
bd355af0
UD
1879
1880Memory not freed:
1881-----------------
1882 Address Size Caller
bc938d3d
UD
18830x08064c48 0x14 at /home/drepper/tst.c:33
18840x08064c60 0x14 at /home/drepper/tst.c:33
18850x08064c78 0x14 at /home/drepper/tst.c:33
18860x08064c90 0x14 at /home/drepper/tst.c:33
bd355af0
UD
1887@end example
1888
1889Suddenly the output makes much more sense and the user can see
1890immediately where the function calls causing the trouble can be found.
1891
9756dfe1
UD
1892Interpreting this output is not complicated. There are at most two
1893different situations being detected. First, @code{free} was called for
1894pointers which were never returned by one of the allocation functions.
bc938d3d 1895This is usually a very bad problem and what this looks like is shown in
9756dfe1
UD
1896the first three lines of the output. Situations like this are quite
1897rare and if they appear they show up very drastically: the program
1898normally crashes.
1899
1900The other situation which is much harder to detect are memory leaks. As
1901you can see in the output the @code{mtrace} function collects all this
1902information and so can say that the program calls an allocation function
1903from line 33 in the source file @file{/home/drepper/tst-mtrace.c} four
1904times without freeing this memory before the program terminates.
bc938d3d 1905Whether this is a real problem remains to be investigated.
9756dfe1 1906
28f540f4 1907@node Obstacks
99a20616 1908@subsection Obstacks
28f540f4
RM
1909@cindex obstacks
1910
1911An @dfn{obstack} is a pool of memory containing a stack of objects. You
1912can create any number of separate obstacks, and then allocate objects in
1913specified obstacks. Within each obstack, the last object allocated must
1914always be the first one freed, but distinct obstacks are independent of
1915each other.
1916
1917Aside from this one constraint of order of freeing, obstacks are totally
1918general: an obstack can contain any number of objects of any size. They
1919are implemented with macros, so allocation is usually very fast as long as
1920the objects are usually small. And the only space overhead per object is
1921the padding needed to start each object on a suitable boundary.
1922
1923@menu
1924* Creating Obstacks:: How to declare an obstack in your program.
1925* Preparing for Obstacks:: Preparations needed before you can
1926 use obstacks.
1927* Allocation in an Obstack:: Allocating objects in an obstack.
1928* Freeing Obstack Objects:: Freeing objects in an obstack.
1929* Obstack Functions:: The obstack functions are both
1930 functions and macros.
1931* Growing Objects:: Making an object bigger by stages.
1932* Extra Fast Growing:: Extra-high-efficiency (though more
1933 complicated) growing objects.
1934* Status of an Obstack:: Inquiries about the status of an obstack.
1935* Obstacks Data Alignment:: Controlling alignment of objects in obstacks.
1936* Obstack Chunks:: How obstacks obtain and release chunks;
1937 efficiency considerations.
a5113b14 1938* Summary of Obstacks::
28f540f4
RM
1939@end menu
1940
1941@node Creating Obstacks
99a20616 1942@subsubsection Creating Obstacks
28f540f4
RM
1943
1944The utilities for manipulating obstacks are declared in the header
1945file @file{obstack.h}.
1946@pindex obstack.h
1947
1948@comment obstack.h
1949@comment GNU
1950@deftp {Data Type} {struct obstack}
1951An obstack is represented by a data structure of type @code{struct
1952obstack}. This structure has a small fixed size; it records the status
1953of the obstack and how to find the space in which objects are allocated.
1954It does not contain any of the objects themselves. You should not try
1955to access the contents of the structure directly; use only the functions
1956described in this chapter.
1957@end deftp
1958
1959You can declare variables of type @code{struct obstack} and use them as
1960obstacks, or you can allocate obstacks dynamically like any other kind
1961of object. Dynamic allocation of obstacks allows your program to have a
1962variable number of different stacks. (You can even allocate an
1963obstack structure in another obstack, but this is rarely useful.)
1964
1965All the functions that work with obstacks require you to specify which
1966obstack to use. You do this with a pointer of type @code{struct obstack
1967*}. In the following, we often say ``an obstack'' when strictly
1968speaking the object at hand is such a pointer.
1969
1970The objects in the obstack are packed into large blocks called
1971@dfn{chunks}. The @code{struct obstack} structure points to a chain of
1972the chunks currently in use.
1973
1974The obstack library obtains a new chunk whenever you allocate an object
1975that won't fit in the previous chunk. Since the obstack library manages
1976chunks automatically, you don't need to pay much attention to them, but
1977you do need to supply a function which the obstack library should use to
1978get a chunk. Usually you supply a function which uses @code{malloc}
1979directly or indirectly. You must also supply a function to free a chunk.
1980These matters are described in the following section.
1981
1982@node Preparing for Obstacks
99a20616 1983@subsubsection Preparing for Using Obstacks
28f540f4
RM
1984
1985Each source file in which you plan to use the obstack functions
1986must include the header file @file{obstack.h}, like this:
1987
1988@smallexample
1989#include <obstack.h>
1990@end smallexample
1991
1992@findex obstack_chunk_alloc
1993@findex obstack_chunk_free
1994Also, if the source file uses the macro @code{obstack_init}, it must
1995declare or define two functions or macros that will be called by the
1996obstack library. One, @code{obstack_chunk_alloc}, is used to allocate
1997the chunks of memory into which objects are packed. The other,
1998@code{obstack_chunk_free}, is used to return chunks when the objects in
1999them are freed. These macros should appear before any use of obstacks
2000in the source file.
2001
2002Usually these are defined to use @code{malloc} via the intermediary
2003@code{xmalloc} (@pxref{Unconstrained Allocation}). This is done with
2004the following pair of macro definitions:
2005
2006@smallexample
2007#define obstack_chunk_alloc xmalloc
2008#define obstack_chunk_free free
2009@end smallexample
2010
2011@noindent
99a20616 2012Though the memory you get using obstacks really comes from @code{malloc},
28f540f4
RM
2013using obstacks is faster because @code{malloc} is called less often, for
2014larger blocks of memory. @xref{Obstack Chunks}, for full details.
2015
2016At run time, before the program can use a @code{struct obstack} object
2017as an obstack, it must initialize the obstack by calling
2018@code{obstack_init}.
2019
2020@comment obstack.h
2021@comment GNU
2022@deftypefun int obstack_init (struct obstack *@var{obstack-ptr})
9f529d7c
AO
2023@safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{@acsmem{}}}
2024@c obstack_init @mtsrace:obstack-ptr @acsmem
2025@c _obstack_begin @acsmem
2026@c chunkfun = obstack_chunk_alloc (suggested malloc)
2027@c freefun = obstack_chunk_free (suggested free)
2028@c *chunkfun @acsmem
2029@c obstack_chunk_alloc user-supplied
2030@c *obstack_alloc_failed_handler user-supplied
2031@c -> print_and_abort (default)
2032@c
2033@c print_and_abort
2034@c _ dup @ascuintl
2035@c fxprintf dup @asucorrupt @aculock @acucorrupt
2036@c exit @acucorrupt?
28f540f4 2037Initialize obstack @var{obstack-ptr} for allocation of objects. This
3cb07217
UD
2038function calls the obstack's @code{obstack_chunk_alloc} function. If
2039allocation of memory fails, the function pointed to by
2040@code{obstack_alloc_failed_handler} is called. The @code{obstack_init}
2041function always returns 1 (Compatibility notice: Former versions of
2042obstack returned 0 if allocation failed).
28f540f4
RM
2043@end deftypefun
2044
2045Here are two examples of how to allocate the space for an obstack and
2046initialize it. First, an obstack that is a static variable:
2047
2048@smallexample
2049static struct obstack myobstack;
2050@dots{}
2051obstack_init (&myobstack);
2052@end smallexample
2053
2054@noindent
2055Second, an obstack that is itself dynamically allocated:
2056
2057@smallexample
2058struct obstack *myobstack_ptr
2059 = (struct obstack *) xmalloc (sizeof (struct obstack));
2060
2061obstack_init (myobstack_ptr);
2062@end smallexample
2063
3cb07217
UD
2064@comment obstack.h
2065@comment GNU
2066@defvar obstack_alloc_failed_handler
2067The value of this variable is a pointer to a function that
2068@code{obstack} uses when @code{obstack_chunk_alloc} fails to allocate
2069memory. The default action is to print a message and abort.
2070You should supply a function that either calls @code{exit}
2071(@pxref{Program Termination}) or @code{longjmp} (@pxref{Non-Local
2072Exits}) and doesn't return.
2073
2074@smallexample
2075void my_obstack_alloc_failed (void)
2076@dots{}
2077obstack_alloc_failed_handler = &my_obstack_alloc_failed;
2078@end smallexample
2079
2080@end defvar
2081
28f540f4 2082@node Allocation in an Obstack
99a20616 2083@subsubsection Allocation in an Obstack
28f540f4
RM
2084@cindex allocation (obstacks)
2085
2086The most direct way to allocate an object in an obstack is with
2087@code{obstack_alloc}, which is invoked almost like @code{malloc}.
2088
2089@comment obstack.h
2090@comment GNU
2091@deftypefun {void *} obstack_alloc (struct obstack *@var{obstack-ptr}, int @var{size})
9f529d7c
AO
2092@safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2093@c obstack_alloc @mtsrace:obstack-ptr @acucorrupt @acsmem
2094@c obstack_blank dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2095@c obstack_finish dup @mtsrace:obstack-ptr @acucorrupt
28f540f4
RM
2096This allocates an uninitialized block of @var{size} bytes in an obstack
2097and returns its address. Here @var{obstack-ptr} specifies which obstack
2098to allocate the block in; it is the address of the @code{struct obstack}
2099object which represents the obstack. Each obstack function or macro
2100requires you to specify an @var{obstack-ptr} as the first argument.
2101
2102This function calls the obstack's @code{obstack_chunk_alloc} function if
3cb07217
UD
2103it needs to allocate a new chunk of memory; it calls
2104@code{obstack_alloc_failed_handler} if allocation of memory by
2105@code{obstack_chunk_alloc} failed.
28f540f4
RM
2106@end deftypefun
2107
2108For example, here is a function that allocates a copy of a string @var{str}
2109in a specific obstack, which is in the variable @code{string_obstack}:
2110
2111@smallexample
2112struct obstack string_obstack;
2113
2114char *
2115copystring (char *string)
2116@{
7cc27f44
UD
2117 size_t len = strlen (string) + 1;
2118 char *s = (char *) obstack_alloc (&string_obstack, len);
2119 memcpy (s, string, len);
28f540f4
RM
2120 return s;
2121@}
2122@end smallexample
2123
2124To allocate a block with specified contents, use the function
2125@code{obstack_copy}, declared like this:
2126
2127@comment obstack.h
2128@comment GNU
2129@deftypefun {void *} obstack_copy (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
9f529d7c
AO
2130@safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2131@c obstack_copy @mtsrace:obstack-ptr @acucorrupt @acsmem
2132@c obstack_grow dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2133@c obstack_finish dup @mtsrace:obstack-ptr @acucorrupt
28f540f4 2134This allocates a block and initializes it by copying @var{size}
3cb07217
UD
2135bytes of data starting at @var{address}. It calls
2136@code{obstack_alloc_failed_handler} if allocation of memory by
2137@code{obstack_chunk_alloc} failed.
28f540f4
RM
2138@end deftypefun
2139
2140@comment obstack.h
2141@comment GNU
2142@deftypefun {void *} obstack_copy0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
9f529d7c
AO
2143@safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2144@c obstack_copy0 @mtsrace:obstack-ptr @acucorrupt @acsmem
2145@c obstack_grow0 dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2146@c obstack_finish dup @mtsrace:obstack-ptr @acucorrupt
28f540f4
RM
2147Like @code{obstack_copy}, but appends an extra byte containing a null
2148character. This extra byte is not counted in the argument @var{size}.
2149@end deftypefun
2150
2151The @code{obstack_copy0} function is convenient for copying a sequence
2152of characters into an obstack as a null-terminated string. Here is an
2153example of its use:
2154
2155@smallexample
2156char *
2157obstack_savestring (char *addr, int size)
2158@{
2159 return obstack_copy0 (&myobstack, addr, size);
2160@}
2161@end smallexample
2162
2163@noindent
2164Contrast this with the previous example of @code{savestring} using
2165@code{malloc} (@pxref{Basic Allocation}).
2166
2167@node Freeing Obstack Objects
99a20616 2168@subsubsection Freeing Objects in an Obstack
28f540f4
RM
2169@cindex freeing (obstacks)
2170
2171To free an object allocated in an obstack, use the function
2172@code{obstack_free}. Since the obstack is a stack of objects, freeing
2173one object automatically frees all other objects allocated more recently
2174in the same obstack.
2175
2176@comment obstack.h
2177@comment GNU
2178@deftypefun void obstack_free (struct obstack *@var{obstack-ptr}, void *@var{object})
9f529d7c
AO
2179@safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{}}}
2180@c obstack_free @mtsrace:obstack-ptr @acucorrupt
2181@c (obstack_free) @mtsrace:obstack-ptr @acucorrupt
2182@c *freefun dup user-supplied
28f540f4
RM
2183If @var{object} is a null pointer, everything allocated in the obstack
2184is freed. Otherwise, @var{object} must be the address of an object
2185allocated in the obstack. Then @var{object} is freed, along with
3ef569c7 2186everything allocated in @var{obstack-ptr} since @var{object}.
28f540f4
RM
2187@end deftypefun
2188
2189Note that if @var{object} is a null pointer, the result is an
99a20616 2190uninitialized obstack. To free all memory in an obstack but leave it
28f540f4
RM
2191valid for further allocation, call @code{obstack_free} with the address
2192of the first object allocated on the obstack:
2193
2194@smallexample
2195obstack_free (obstack_ptr, first_object_allocated_ptr);
2196@end smallexample
2197
2198Recall that the objects in an obstack are grouped into chunks. When all
2199the objects in a chunk become free, the obstack library automatically
2200frees the chunk (@pxref{Preparing for Obstacks}). Then other
2201obstacks, or non-obstack allocation, can reuse the space of the chunk.
2202
2203@node Obstack Functions
99a20616 2204@subsubsection Obstack Functions and Macros
28f540f4
RM
2205@cindex macros
2206
2207The interfaces for using obstacks may be defined either as functions or
2208as macros, depending on the compiler. The obstack facility works with
f65fd747 2209all C compilers, including both @w{ISO C} and traditional C, but there are
28f540f4
RM
2210precautions you must take if you plan to use compilers other than GNU C.
2211
f65fd747 2212If you are using an old-fashioned @w{non-ISO C} compiler, all the obstack
28f540f4
RM
2213``functions'' are actually defined only as macros. You can call these
2214macros like functions, but you cannot use them in any other way (for
2215example, you cannot take their address).
2216
2217Calling the macros requires a special precaution: namely, the first
2218operand (the obstack pointer) may not contain any side effects, because
2219it may be computed more than once. For example, if you write this:
2220
2221@smallexample
2222obstack_alloc (get_obstack (), 4);
2223@end smallexample
2224
2225@noindent
2226you will find that @code{get_obstack} may be called several times.
2227If you use @code{*obstack_list_ptr++} as the obstack pointer argument,
2228you will get very strange results since the incrementation may occur
2229several times.
2230
f65fd747 2231In @w{ISO C}, each function has both a macro definition and a function
28f540f4
RM
2232definition. The function definition is used if you take the address of the
2233function without calling it. An ordinary call uses the macro definition by
2234default, but you can request the function definition instead by writing the
2235function name in parentheses, as shown here:
2236
2237@smallexample
2238char *x;
2239void *(*funcp) ();
2240/* @r{Use the macro}. */
2241x = (char *) obstack_alloc (obptr, size);
2242/* @r{Call the function}. */
2243x = (char *) (obstack_alloc) (obptr, size);
2244/* @r{Take the address of the function}. */
2245funcp = obstack_alloc;
2246@end smallexample
2247
2248@noindent
f65fd747 2249This is the same situation that exists in @w{ISO C} for the standard library
28f540f4
RM
2250functions. @xref{Macro Definitions}.
2251
2252@strong{Warning:} When you do use the macros, you must observe the
f65fd747 2253precaution of avoiding side effects in the first operand, even in @w{ISO C}.
28f540f4
RM
2254
2255If you use the GNU C compiler, this precaution is not necessary, because
2256various language extensions in GNU C permit defining the macros so as to
2257compute each argument only once.
2258
2259@node Growing Objects
99a20616 2260@subsubsection Growing Objects
28f540f4
RM
2261@cindex growing objects (in obstacks)
2262@cindex changing the size of a block (obstacks)
2263
99a20616 2264Because memory in obstack chunks is used sequentially, it is possible to
28f540f4
RM
2265build up an object step by step, adding one or more bytes at a time to the
2266end of the object. With this technique, you do not need to know how much
2267data you will put in the object until you come to the end of it. We call
2268this the technique of @dfn{growing objects}. The special functions
2269for adding data to the growing object are described in this section.
2270
2271You don't need to do anything special when you start to grow an object.
2272Using one of the functions to add data to the object automatically
2273starts it. However, it is necessary to say explicitly when the object is
2274finished. This is done with the function @code{obstack_finish}.
2275
2276The actual address of the object thus built up is not known until the
2277object is finished. Until then, it always remains possible that you will
2278add so much data that the object must be copied into a new chunk.
2279
2280While the obstack is in use for a growing object, you cannot use it for
2281ordinary allocation of another object. If you try to do so, the space
2282already added to the growing object will become part of the other object.
2283
2284@comment obstack.h
2285@comment GNU
2286@deftypefun void obstack_blank (struct obstack *@var{obstack-ptr}, int @var{size})
9f529d7c
AO
2287@safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2288@c obstack_blank @mtsrace:obstack-ptr @acucorrupt @acsmem
2289@c _obstack_newchunk @mtsrace:obstack-ptr @acucorrupt @acsmem
2290@c *chunkfun dup @acsmem
2291@c *obstack_alloc_failed_handler dup user-supplied
2292@c *freefun
2293@c obstack_blank_fast dup @mtsrace:obstack-ptr
28f540f4
RM
2294The most basic function for adding to a growing object is
2295@code{obstack_blank}, which adds space without initializing it.
2296@end deftypefun
2297
2298@comment obstack.h
2299@comment GNU
2300@deftypefun void obstack_grow (struct obstack *@var{obstack-ptr}, void *@var{data}, int @var{size})
9f529d7c
AO
2301@safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2302@c obstack_grow @mtsrace:obstack-ptr @acucorrupt @acsmem
2303@c _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2304@c memcpy ok
28f540f4
RM
2305To add a block of initialized space, use @code{obstack_grow}, which is
2306the growing-object analogue of @code{obstack_copy}. It adds @var{size}
2307bytes of data to the growing object, copying the contents from
2308@var{data}.
2309@end deftypefun
2310
2311@comment obstack.h
2312@comment GNU
2313@deftypefun void obstack_grow0 (struct obstack *@var{obstack-ptr}, void *@var{data}, int @var{size})
9f529d7c
AO
2314@safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2315@c obstack_grow0 @mtsrace:obstack-ptr @acucorrupt @acsmem
2316@c (no sequence point between storing NUL and incrementing next_free)
2317@c (multiple changes to next_free => @acucorrupt)
2318@c _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2319@c memcpy ok
28f540f4
RM
2320This is the growing-object analogue of @code{obstack_copy0}. It adds
2321@var{size} bytes copied from @var{data}, followed by an additional null
2322character.
2323@end deftypefun
2324
2325@comment obstack.h
2326@comment GNU
2327@deftypefun void obstack_1grow (struct obstack *@var{obstack-ptr}, char @var{c})
9f529d7c
AO
2328@safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2329@c obstack_1grow @mtsrace:obstack-ptr @acucorrupt @acsmem
2330@c _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2331@c obstack_1grow_fast dup @mtsrace:obstack-ptr @acucorrupt @acsmem
28f540f4
RM
2332To add one character at a time, use the function @code{obstack_1grow}.
2333It adds a single byte containing @var{c} to the growing object.
2334@end deftypefun
2335
2c6fe0bd
UD
2336@comment obstack.h
2337@comment GNU
2338@deftypefun void obstack_ptr_grow (struct obstack *@var{obstack-ptr}, void *@var{data})
9f529d7c
AO
2339@safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2340@c obstack_ptr_grow @mtsrace:obstack-ptr @acucorrupt @acsmem
2341@c _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2342@c obstack_ptr_grow_fast dup @mtsrace:obstack-ptr
2c6fe0bd
UD
2343Adding the value of a pointer one can use the function
2344@code{obstack_ptr_grow}. It adds @code{sizeof (void *)} bytes
2345containing the value of @var{data}.
2346@end deftypefun
2347
2348@comment obstack.h
2349@comment GNU
2350@deftypefun void obstack_int_grow (struct obstack *@var{obstack-ptr}, int @var{data})
9f529d7c
AO
2351@safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2352@c obstack_int_grow @mtsrace:obstack-ptr @acucorrupt @acsmem
2353@c _obstack_newchunk dup @mtsrace:obstack-ptr @acucorrupt @acsmem
2354@c obstack_int_grow_fast dup @mtsrace:obstack-ptr
2c6fe0bd
UD
2355A single value of type @code{int} can be added by using the
2356@code{obstack_int_grow} function. It adds @code{sizeof (int)} bytes to
2357the growing object and initializes them with the value of @var{data}.
2358@end deftypefun
2359
28f540f4
RM
2360@comment obstack.h
2361@comment GNU
2362@deftypefun {void *} obstack_finish (struct obstack *@var{obstack-ptr})
9f529d7c
AO
2363@safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{}}}
2364@c obstack_finish @mtsrace:obstack-ptr @acucorrupt
28f540f4
RM
2365When you are finished growing the object, use the function
2366@code{obstack_finish} to close it off and return its final address.
2367
2368Once you have finished the object, the obstack is available for ordinary
2369allocation or for growing another object.
2370
2371This function can return a null pointer under the same conditions as
2372@code{obstack_alloc} (@pxref{Allocation in an Obstack}).
2373@end deftypefun
2374
2375When you build an object by growing it, you will probably need to know
2376afterward how long it became. You need not keep track of this as you grow
2377the object, because you can find out the length from the obstack just
2378before finishing the object with the function @code{obstack_object_size},
2379declared as follows:
2380
2381@comment obstack.h
2382@comment GNU
2383@deftypefun int obstack_object_size (struct obstack *@var{obstack-ptr})
9f529d7c 2384@safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
28f540f4
RM
2385This function returns the current size of the growing object, in bytes.
2386Remember to call this function @emph{before} finishing the object.
2387After it is finished, @code{obstack_object_size} will return zero.
2388@end deftypefun
2389
2390If you have started growing an object and wish to cancel it, you should
2391finish it and then free it, like this:
2392
2393@smallexample
2394obstack_free (obstack_ptr, obstack_finish (obstack_ptr));
2395@end smallexample
2396
2397@noindent
2398This has no effect if no object was growing.
2399
2400@cindex shrinking objects
2401You can use @code{obstack_blank} with a negative size argument to make
2402the current object smaller. Just don't try to shrink it beyond zero
2403length---there's no telling what will happen if you do that.
2404
2405@node Extra Fast Growing
99a20616 2406@subsubsection Extra Fast Growing Objects
28f540f4
RM
2407@cindex efficiency and obstacks
2408
2409The usual functions for growing objects incur overhead for checking
2410whether there is room for the new growth in the current chunk. If you
2411are frequently constructing objects in small steps of growth, this
2412overhead can be significant.
2413
2414You can reduce the overhead by using special ``fast growth''
2415functions that grow the object without checking. In order to have a
2416robust program, you must do the checking yourself. If you do this checking
2417in the simplest way each time you are about to add data to the object, you
2418have not saved anything, because that is what the ordinary growth
2419functions do. But if you can arrange to check less often, or check
2420more efficiently, then you make the program faster.
2421
2422The function @code{obstack_room} returns the amount of room available
2423in the current chunk. It is declared as follows:
2424
2425@comment obstack.h
2426@comment GNU
2427@deftypefun int obstack_room (struct obstack *@var{obstack-ptr})
9f529d7c 2428@safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
28f540f4
RM
2429This returns the number of bytes that can be added safely to the current
2430growing object (or to an object about to be started) in obstack
3ef569c7 2431@var{obstack-ptr} using the fast growth functions.
28f540f4
RM
2432@end deftypefun
2433
2434While you know there is room, you can use these fast growth functions
2435for adding data to a growing object:
2436
2437@comment obstack.h
2438@comment GNU
2439@deftypefun void obstack_1grow_fast (struct obstack *@var{obstack-ptr}, char @var{c})
9f529d7c
AO
2440@safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acunsafe{@acucorrupt{} @acsmem{}}}
2441@c obstack_1grow_fast @mtsrace:obstack-ptr @acucorrupt @acsmem
2442@c (no sequence point between copying c and incrementing next_free)
28f540f4
RM
2443The function @code{obstack_1grow_fast} adds one byte containing the
2444character @var{c} to the growing object in obstack @var{obstack-ptr}.
2445@end deftypefun
2446
2c6fe0bd
UD
2447@comment obstack.h
2448@comment GNU
2449@deftypefun void obstack_ptr_grow_fast (struct obstack *@var{obstack-ptr}, void *@var{data})
9f529d7c
AO
2450@safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
2451@c obstack_ptr_grow_fast @mtsrace:obstack-ptr
2c6fe0bd
UD
2452The function @code{obstack_ptr_grow_fast} adds @code{sizeof (void *)}
2453bytes containing the value of @var{data} to the growing object in
2454obstack @var{obstack-ptr}.
2455@end deftypefun
2456
2457@comment obstack.h
2458@comment GNU
2459@deftypefun void obstack_int_grow_fast (struct obstack *@var{obstack-ptr}, int @var{data})
9f529d7c
AO
2460@safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
2461@c obstack_int_grow_fast @mtsrace:obstack-ptr
2c6fe0bd
UD
2462The function @code{obstack_int_grow_fast} adds @code{sizeof (int)} bytes
2463containing the value of @var{data} to the growing object in obstack
2464@var{obstack-ptr}.
2465@end deftypefun
2466
28f540f4
RM
2467@comment obstack.h
2468@comment GNU
2469@deftypefun void obstack_blank_fast (struct obstack *@var{obstack-ptr}, int @var{size})
9f529d7c
AO
2470@safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
2471@c obstack_blank_fast @mtsrace:obstack-ptr
28f540f4
RM
2472The function @code{obstack_blank_fast} adds @var{size} bytes to the
2473growing object in obstack @var{obstack-ptr} without initializing them.
2474@end deftypefun
2475
2476When you check for space using @code{obstack_room} and there is not
2477enough room for what you want to add, the fast growth functions
2478are not safe. In this case, simply use the corresponding ordinary
2479growth function instead. Very soon this will copy the object to a
a5113b14 2480new chunk; then there will be lots of room available again.
28f540f4
RM
2481
2482So, each time you use an ordinary growth function, check afterward for
2483sufficient space using @code{obstack_room}. Once the object is copied
2484to a new chunk, there will be plenty of space again, so the program will
2485start using the fast growth functions again.
2486
2487Here is an example:
2488
2489@smallexample
2490@group
2491void
2492add_string (struct obstack *obstack, const char *ptr, int len)
2493@{
2494 while (len > 0)
2495 @{
2496 int room = obstack_room (obstack);
2497 if (room == 0)
2498 @{
cf822e3c 2499 /* @r{Not enough room. Add one character slowly,}
28f540f4
RM
2500 @r{which may copy to a new chunk and make room.} */
2501 obstack_1grow (obstack, *ptr++);
2502 len--;
2503 @}
a5113b14 2504 else
28f540f4
RM
2505 @{
2506 if (room > len)
2507 room = len;
2508 /* @r{Add fast as much as we have room for.} */
2509 len -= room;
2510 while (room-- > 0)
2511 obstack_1grow_fast (obstack, *ptr++);
2512 @}
2513 @}
2514@}
2515@end group
2516@end smallexample
2517
2518@node Status of an Obstack
99a20616 2519@subsubsection Status of an Obstack
28f540f4
RM
2520@cindex obstack status
2521@cindex status of obstack
2522
2523Here are functions that provide information on the current status of
2524allocation in an obstack. You can use them to learn about an object while
2525still growing it.
2526
2527@comment obstack.h
2528@comment GNU
2529@deftypefun {void *} obstack_base (struct obstack *@var{obstack-ptr})
9f529d7c 2530@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acsafe{}}
28f540f4
RM
2531This function returns the tentative address of the beginning of the
2532currently growing object in @var{obstack-ptr}. If you finish the object
2533immediately, it will have that address. If you make it larger first, it
2534may outgrow the current chunk---then its address will change!
2535
2536If no object is growing, this value says where the next object you
2537allocate will start (once again assuming it fits in the current
2538chunk).
2539@end deftypefun
2540
2541@comment obstack.h
2542@comment GNU
2543@deftypefun {void *} obstack_next_free (struct obstack *@var{obstack-ptr})
9f529d7c 2544@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acsafe{}}
28f540f4
RM
2545This function returns the address of the first free byte in the current
2546chunk of obstack @var{obstack-ptr}. This is the end of the currently
2547growing object. If no object is growing, @code{obstack_next_free}
2548returns the same value as @code{obstack_base}.
2549@end deftypefun
2550
2551@comment obstack.h
2552@comment GNU
2553@deftypefun int obstack_object_size (struct obstack *@var{obstack-ptr})
9f529d7c
AO
2554@c dup
2555@safety{@prelim{}@mtsafe{@mtsrace{:obstack-ptr}}@assafe{}@acsafe{}}
28f540f4
RM
2556This function returns the size in bytes of the currently growing object.
2557This is equivalent to
2558
2559@smallexample
2560obstack_next_free (@var{obstack-ptr}) - obstack_base (@var{obstack-ptr})
2561@end smallexample
2562@end deftypefun
2563
2564@node Obstacks Data Alignment
99a20616 2565@subsubsection Alignment of Data in Obstacks
28f540f4
RM
2566@cindex alignment (in obstacks)
2567
2568Each obstack has an @dfn{alignment boundary}; each object allocated in
2569the obstack automatically starts on an address that is a multiple of the
11883883
RM
2570specified boundary. By default, this boundary is aligned so that
2571the object can hold any type of data.
28f540f4
RM
2572
2573To access an obstack's alignment boundary, use the macro
2574@code{obstack_alignment_mask}, whose function prototype looks like
2575this:
2576
2577@comment obstack.h
2578@comment GNU
2579@deftypefn Macro int obstack_alignment_mask (struct obstack *@var{obstack-ptr})
9f529d7c 2580@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
2581The value is a bit mask; a bit that is 1 indicates that the corresponding
2582bit in the address of an object should be 0. The mask value should be one
2583less than a power of 2; the effect is that all object addresses are
11883883
RM
2584multiples of that power of 2. The default value of the mask is a value
2585that allows aligned objects to hold any type of data: for example, if
2586its value is 3, any type of data can be stored at locations whose
28f540f4
RM
2587addresses are multiples of 4. A mask value of 0 means an object can start
2588on any multiple of 1 (that is, no alignment is required).
2589
2590The expansion of the macro @code{obstack_alignment_mask} is an lvalue,
2591so you can alter the mask by assignment. For example, this statement:
2592
2593@smallexample
2594obstack_alignment_mask (obstack_ptr) = 0;
2595@end smallexample
2596
2597@noindent
2598has the effect of turning off alignment processing in the specified obstack.
2599@end deftypefn
2600
2601Note that a change in alignment mask does not take effect until
2602@emph{after} the next time an object is allocated or finished in the
2603obstack. If you are not growing an object, you can make the new
2604alignment mask take effect immediately by calling @code{obstack_finish}.
2605This will finish a zero-length object and then do proper alignment for
2606the next object.
2607
2608@node Obstack Chunks
99a20616 2609@subsubsection Obstack Chunks
28f540f4
RM
2610@cindex efficiency of chunks
2611@cindex chunks
2612
2613Obstacks work by allocating space for themselves in large chunks, and
2614then parceling out space in the chunks to satisfy your requests. Chunks
2615are normally 4096 bytes long unless you specify a different chunk size.
2616The chunk size includes 8 bytes of overhead that are not actually used
2617for storing objects. Regardless of the specified size, longer chunks
2618will be allocated when necessary for long objects.
2619
2620The obstack library allocates chunks by calling the function
2621@code{obstack_chunk_alloc}, which you must define. When a chunk is no
2622longer needed because you have freed all the objects in it, the obstack
2623library frees the chunk by calling @code{obstack_chunk_free}, which you
2624must also define.
2625
2626These two must be defined (as macros) or declared (as functions) in each
2627source file that uses @code{obstack_init} (@pxref{Creating Obstacks}).
2628Most often they are defined as macros like this:
2629
2630@smallexample
bd355af0 2631#define obstack_chunk_alloc malloc
28f540f4
RM
2632#define obstack_chunk_free free
2633@end smallexample
2634
2635Note that these are simple macros (no arguments). Macro definitions with
2636arguments will not work! It is necessary that @code{obstack_chunk_alloc}
2637or @code{obstack_chunk_free}, alone, expand into a function name if it is
2638not itself a function name.
2639
2640If you allocate chunks with @code{malloc}, the chunk size should be a
2641power of 2. The default chunk size, 4096, was chosen because it is long
2642enough to satisfy many typical requests on the obstack yet short enough
2643not to waste too much memory in the portion of the last chunk not yet used.
2644
2645@comment obstack.h
2646@comment GNU
2647@deftypefn Macro int obstack_chunk_size (struct obstack *@var{obstack-ptr})
9f529d7c 2648@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4
RM
2649This returns the chunk size of the given obstack.
2650@end deftypefn
2651
2652Since this macro expands to an lvalue, you can specify a new chunk size by
2653assigning it a new value. Doing so does not affect the chunks already
2654allocated, but will change the size of chunks allocated for that particular
2655obstack in the future. It is unlikely to be useful to make the chunk size
2656smaller, but making it larger might improve efficiency if you are
2657allocating many objects whose size is comparable to the chunk size. Here
2658is how to do so cleanly:
2659
2660@smallexample
2661if (obstack_chunk_size (obstack_ptr) < @var{new-chunk-size})
2662 obstack_chunk_size (obstack_ptr) = @var{new-chunk-size};
2663@end smallexample
2664
2665@node Summary of Obstacks
99a20616 2666@subsubsection Summary of Obstack Functions
28f540f4
RM
2667
2668Here is a summary of all the functions associated with obstacks. Each
2669takes the address of an obstack (@code{struct obstack *}) as its first
2670argument.
2671
2672@table @code
2673@item void obstack_init (struct obstack *@var{obstack-ptr})
2674Initialize use of an obstack. @xref{Creating Obstacks}.
2675
2676@item void *obstack_alloc (struct obstack *@var{obstack-ptr}, int @var{size})
2677Allocate an object of @var{size} uninitialized bytes.
2678@xref{Allocation in an Obstack}.
2679
2680@item void *obstack_copy (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2681Allocate an object of @var{size} bytes, with contents copied from
2682@var{address}. @xref{Allocation in an Obstack}.
2683
2684@item void *obstack_copy0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2685Allocate an object of @var{size}+1 bytes, with @var{size} of them copied
2686from @var{address}, followed by a null character at the end.
2687@xref{Allocation in an Obstack}.
2688
2689@item void obstack_free (struct obstack *@var{obstack-ptr}, void *@var{object})
2690Free @var{object} (and everything allocated in the specified obstack
2691more recently than @var{object}). @xref{Freeing Obstack Objects}.
2692
2693@item void obstack_blank (struct obstack *@var{obstack-ptr}, int @var{size})
2694Add @var{size} uninitialized bytes to a growing object.
2695@xref{Growing Objects}.
2696
2697@item void obstack_grow (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2698Add @var{size} bytes, copied from @var{address}, to a growing object.
2699@xref{Growing Objects}.
2700
2701@item void obstack_grow0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2702Add @var{size} bytes, copied from @var{address}, to a growing object,
2703and then add another byte containing a null character. @xref{Growing
2704Objects}.
2705
2706@item void obstack_1grow (struct obstack *@var{obstack-ptr}, char @var{data-char})
2707Add one byte containing @var{data-char} to a growing object.
2708@xref{Growing Objects}.
2709
2710@item void *obstack_finish (struct obstack *@var{obstack-ptr})
2711Finalize the object that is growing and return its permanent address.
2712@xref{Growing Objects}.
2713
2714@item int obstack_object_size (struct obstack *@var{obstack-ptr})
2715Get the current size of the currently growing object. @xref{Growing
2716Objects}.
2717
2718@item void obstack_blank_fast (struct obstack *@var{obstack-ptr}, int @var{size})
2719Add @var{size} uninitialized bytes to a growing object without checking
2720that there is enough room. @xref{Extra Fast Growing}.
2721
2722@item void obstack_1grow_fast (struct obstack *@var{obstack-ptr}, char @var{data-char})
2723Add one byte containing @var{data-char} to a growing object without
2724checking that there is enough room. @xref{Extra Fast Growing}.
2725
2726@item int obstack_room (struct obstack *@var{obstack-ptr})
2727Get the amount of room now available for growing the current object.
2728@xref{Extra Fast Growing}.
2729
2730@item int obstack_alignment_mask (struct obstack *@var{obstack-ptr})
2731The mask used for aligning the beginning of an object. This is an
2732lvalue. @xref{Obstacks Data Alignment}.
2733
2734@item int obstack_chunk_size (struct obstack *@var{obstack-ptr})
2735The size for allocating chunks. This is an lvalue. @xref{Obstack Chunks}.
2736
2737@item void *obstack_base (struct obstack *@var{obstack-ptr})
2738Tentative starting address of the currently growing object.
2739@xref{Status of an Obstack}.
2740
2741@item void *obstack_next_free (struct obstack *@var{obstack-ptr})
2742Address just after the end of the currently growing object.
2743@xref{Status of an Obstack}.
2744@end table
2745
2746@node Variable Size Automatic
99a20616 2747@subsection Automatic Storage with Variable Size
28f540f4
RM
2748@cindex automatic freeing
2749@cindex @code{alloca} function
2750@cindex automatic storage with variable size
2751
2752The function @code{alloca} supports a kind of half-dynamic allocation in
2753which blocks are allocated dynamically but freed automatically.
2754
2755Allocating a block with @code{alloca} is an explicit action; you can
2756allocate as many blocks as you wish, and compute the size at run time. But
2757all the blocks are freed when you exit the function that @code{alloca} was
2758called from, just as if they were automatic variables declared in that
2759function. There is no way to free the space explicitly.
2760
2761The prototype for @code{alloca} is in @file{stdlib.h}. This function is
2762a BSD extension.
2763@pindex stdlib.h
2764
2765@comment stdlib.h
2766@comment GNU, BSD
cc6e48bc 2767@deftypefun {void *} alloca (size_t @var{size})
9f529d7c 2768@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28f540f4 2769The return value of @code{alloca} is the address of a block of @var{size}
99a20616 2770bytes of memory, allocated in the stack frame of the calling function.
28f540f4
RM
2771@end deftypefun
2772
2773Do not use @code{alloca} inside the arguments of a function call---you
2774will get unpredictable results, because the stack space for the
2775@code{alloca} would appear on the stack in the middle of the space for
2776the function arguments. An example of what to avoid is @code{foo (x,
2777alloca (4), y)}.
2778@c This might get fixed in future versions of GCC, but that won't make
2779@c it safe with compilers generally.
2780
2781@menu
2782* Alloca Example:: Example of using @code{alloca}.
2783* Advantages of Alloca:: Reasons to use @code{alloca}.
2784* Disadvantages of Alloca:: Reasons to avoid @code{alloca}.
2785* GNU C Variable-Size Arrays:: Only in GNU C, here is an alternative
2786 method of allocating dynamically and
2787 freeing automatically.
2788@end menu
2789
2790@node Alloca Example
99a20616 2791@subsubsection @code{alloca} Example
28f540f4 2792
bc938d3d
UD
2793As an example of the use of @code{alloca}, here is a function that opens
2794a file name made from concatenating two argument strings, and returns a
2795file descriptor or minus one signifying failure:
28f540f4
RM
2796
2797@smallexample
2798int
2799open2 (char *str1, char *str2, int flags, int mode)
2800@{
2801 char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
a5113b14 2802 stpcpy (stpcpy (name, str1), str2);
28f540f4
RM
2803 return open (name, flags, mode);
2804@}
2805@end smallexample
2806
2807@noindent
2808Here is how you would get the same results with @code{malloc} and
2809@code{free}:
2810
2811@smallexample
2812int
2813open2 (char *str1, char *str2, int flags, int mode)
2814@{
2815 char *name = (char *) malloc (strlen (str1) + strlen (str2) + 1);
2816 int desc;
2817 if (name == 0)
2818 fatal ("virtual memory exceeded");
a5113b14 2819 stpcpy (stpcpy (name, str1), str2);
28f540f4
RM
2820 desc = open (name, flags, mode);
2821 free (name);
2822 return desc;
2823@}
2824@end smallexample
2825
2826As you can see, it is simpler with @code{alloca}. But @code{alloca} has
2827other, more important advantages, and some disadvantages.
2828
2829@node Advantages of Alloca
99a20616 2830@subsubsection Advantages of @code{alloca}
28f540f4
RM
2831
2832Here are the reasons why @code{alloca} may be preferable to @code{malloc}:
2833
2834@itemize @bullet
2835@item
2836Using @code{alloca} wastes very little space and is very fast. (It is
2837open-coded by the GNU C compiler.)
2838
2839@item
2840Since @code{alloca} does not have separate pools for different sizes of
3ef569c7 2841blocks, space used for any size block can be reused for any other size.
99a20616 2842@code{alloca} does not cause memory fragmentation.
28f540f4
RM
2843
2844@item
2845@cindex longjmp
2846Nonlocal exits done with @code{longjmp} (@pxref{Non-Local Exits})
2847automatically free the space allocated with @code{alloca} when they exit
2848through the function that called @code{alloca}. This is the most
2849important reason to use @code{alloca}.
2850
2851To illustrate this, suppose you have a function
2852@code{open_or_report_error} which returns a descriptor, like
2853@code{open}, if it succeeds, but does not return to its caller if it
2854fails. If the file cannot be opened, it prints an error message and
2855jumps out to the command level of your program using @code{longjmp}.
2856Let's change @code{open2} (@pxref{Alloca Example}) to use this
2857subroutine:@refill
2858
2859@smallexample
2860int
2861open2 (char *str1, char *str2, int flags, int mode)
2862@{
2863 char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
a5113b14 2864 stpcpy (stpcpy (name, str1), str2);
28f540f4
RM
2865 return open_or_report_error (name, flags, mode);
2866@}
2867@end smallexample
2868
2869@noindent
99a20616 2870Because of the way @code{alloca} works, the memory it allocates is
28f540f4
RM
2871freed even when an error occurs, with no special effort required.
2872
2873By contrast, the previous definition of @code{open2} (which uses
99a20616 2874@code{malloc} and @code{free}) would develop a memory leak if it were
28f540f4
RM
2875changed in this way. Even if you are willing to make more changes to
2876fix it, there is no easy way to do so.
2877@end itemize
2878
2879@node Disadvantages of Alloca
99a20616 2880@subsubsection Disadvantages of @code{alloca}
28f540f4
RM
2881
2882@cindex @code{alloca} disadvantages
2883@cindex disadvantages of @code{alloca}
2884These are the disadvantages of @code{alloca} in comparison with
2885@code{malloc}:
2886
2887@itemize @bullet
2888@item
99a20616 2889If you try to allocate more memory than the machine can provide, you
28f540f4
RM
2890don't get a clean error message. Instead you get a fatal signal like
2891the one you would get from an infinite recursion; probably a
2892segmentation violation (@pxref{Program Error Signals}).
2893
2894@item
a7a93d50 2895Some @nongnusystems{} fail to support @code{alloca}, so it is less
28f540f4
RM
2896portable. However, a slower emulation of @code{alloca} written in C
2897is available for use on systems with this deficiency.
2898@end itemize
2899
2900@node GNU C Variable-Size Arrays
99a20616 2901@subsubsection GNU C Variable-Size Arrays
28f540f4
RM
2902@cindex variable-sized arrays
2903
2904In GNU C, you can replace most uses of @code{alloca} with an array of
2905variable size. Here is how @code{open2} would look then:
2906
2907@smallexample
2908int open2 (char *str1, char *str2, int flags, int mode)
2909@{
2910 char name[strlen (str1) + strlen (str2) + 1];
a5113b14 2911 stpcpy (stpcpy (name, str1), str2);
28f540f4
RM
2912 return open (name, flags, mode);
2913@}
2914@end smallexample
2915
2916But @code{alloca} is not always equivalent to a variable-sized array, for
2917several reasons:
2918
2919@itemize @bullet
2920@item
2921A variable size array's space is freed at the end of the scope of the
2922name of the array. The space allocated with @code{alloca}
2923remains until the end of the function.
2924
2925@item
2926It is possible to use @code{alloca} within a loop, allocating an
2927additional block on each iteration. This is impossible with
2928variable-sized arrays.
2929@end itemize
2930
48b22986 2931@strong{NB:} If you mix use of @code{alloca} and variable-sized arrays
28f540f4
RM
2932within one function, exiting a scope in which a variable-sized array was
2933declared frees all blocks allocated with @code{alloca} during the
2934execution of that scope.
2935
99a20616
UD
2936
2937@node Resizing the Data Segment
2938@section Resizing the Data Segment
2939
2940The symbols in this section are declared in @file{unistd.h}.
2941
2942You will not normally use the functions in this section, because the
2943functions described in @ref{Memory Allocation} are easier to use. Those
1f77f049 2944are interfaces to a @glibcadj{} memory allocator that uses the
99a20616
UD
2945functions below itself. The functions below are simple interfaces to
2946system calls.
2947
2948@comment unistd.h
2949@comment BSD
2950@deftypefun int brk (void *@var{addr})
9f529d7c 2951@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
99a20616
UD
2952
2953@code{brk} sets the high end of the calling process' data segment to
2954@var{addr}.
2955
2956The address of the end of a segment is defined to be the address of the
2957last byte in the segment plus 1.
2958
2959The function has no effect if @var{addr} is lower than the low end of
3ef569c7 2960the data segment. (This is considered success, by the way.)
99a20616
UD
2961
2962The function fails if it would cause the data segment to overlap another
68979757 2963segment or exceed the process' data storage limit (@pxref{Limits on
99a20616
UD
2964Resources}).
2965
2966The function is named for a common historical case where data storage
2967and the stack are in the same segment. Data storage allocation grows
2968upward from the bottom of the segment while the stack grows downward
2969toward it from the top of the segment and the curtain between them is
2970called the @dfn{break}.
2971
2972The return value is zero on success. On failure, the return value is
68979757 2973@code{-1} and @code{errno} is set accordingly. The following @code{errno}
99a20616
UD
2974values are specific to this function:
2975
2976@table @code
2977@item ENOMEM
2978The request would cause the data segment to overlap another segment or
2979exceed the process' data storage limit.
2980@end table
2981
2982@c The Brk system call in Linux (as opposed to the GNU C Library function)
2983@c is considerably different. It always returns the new end of the data
2984@c segment, whether it succeeds or fails. The GNU C library Brk determines
bbf70ae9 2985@c it's a failure if and only if the system call returns an address less
99a20616
UD
2986@c than the address requested.
2987
2988@end deftypefun
2989
2990
2991@comment unistd.h
2992@comment BSD
d6868416 2993@deftypefun void *sbrk (ptrdiff_t @var{delta})
9f529d7c
AO
2994@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2995
99a20616
UD
2996This function is the same as @code{brk} except that you specify the new
2997end of the data segment as an offset @var{delta} from the current end
2998and on success the return value is the address of the resulting end of
2999the data segment instead of zero.
3000
3001This means you can use @samp{sbrk(0)} to find out what the current end
3002of the data segment is.
3003
3004@end deftypefun
3005
3006
3007
3008@node Locking Pages
3009@section Locking Pages
3010@cindex locking pages
3011@cindex memory lock
3012@cindex paging
3013
3014You can tell the system to associate a particular virtual memory page
11bf311e 3015with a real page frame and keep it that way --- i.e., cause the page to
99a20616
UD
3016be paged in if it isn't already and mark it so it will never be paged
3017out and consequently will never cause a page fault. This is called
3018@dfn{locking} a page.
3019
3020The functions in this chapter lock and unlock the calling process'
3021pages.
3022
3023@menu
3024* Why Lock Pages:: Reasons to read this section.
3025* Locked Memory Details:: Everything you need to know locked
3026 memory
3027* Page Lock Functions:: Here's how to do it.
3028@end menu
3029
3030@node Why Lock Pages
3031@subsection Why Lock Pages
3032
3033Because page faults cause paged out pages to be paged in transparently,
68979757 3034a process rarely needs to be concerned about locking pages. However,
99a20616
UD
3035there are two reasons people sometimes are:
3036
3037@itemize @bullet
3038
3039@item
3040Speed. A page fault is transparent only insofar as the process is not
3041sensitive to how long it takes to do a simple memory access. Time-critical
3042processes, especially realtime processes, may not be able to wait or
3043may not be able to tolerate variance in execution speed.
3044@cindex realtime processing
3045@cindex speed of execution
3046
3047A process that needs to lock pages for this reason probably also needs
3048priority among other processes for use of the CPU. @xref{Priority}.
3049
3050In some cases, the programmer knows better than the system's demand
3051paging allocator which pages should remain in real memory to optimize
3052system performance. In this case, locking pages can help.
3053
3054@item
3055Privacy. If you keep secrets in virtual memory and that virtual memory
3056gets paged out, that increases the chance that the secrets will get out.
3057If a password gets written out to disk swap space, for example, it might
3058still be there long after virtual and real memory have been wiped clean.
3059
3060@end itemize
3061
3062Be aware that when you lock a page, that's one fewer page frame that can
3063be used to back other virtual memory (by the same or other processes),
3064which can mean more page faults, which means the system runs more
3065slowly. In fact, if you lock enough memory, some programs may not be
3066able to run at all for lack of real memory.
3067
3068@node Locked Memory Details
3069@subsection Locked Memory Details
3070
3071A memory lock is associated with a virtual page, not a real frame. The
3072paging rule is: If a frame backs at least one locked page, don't page it
3073out.
3074
11bf311e 3075Memory locks do not stack. I.e., you can't lock a particular page twice
99a20616
UD
3076so that it has to be unlocked twice before it is truly unlocked. It is
3077either locked or it isn't.
3078
3079A memory lock persists until the process that owns the memory explicitly
3080unlocks it. (But process termination and exec cause the virtual memory
3081to cease to exist, which you might say means it isn't locked any more).
3082
3083Memory locks are not inherited by child processes. (But note that on a
3084modern Unix system, immediately after a fork, the parent's and the
3085child's virtual address space are backed by the same real page frames,
3086so the child enjoys the parent's locks). @xref{Creating a Process}.
3087
3088Because of its ability to impact other processes, only the superuser can
3089lock a page. Any process can unlock its own page.
3090
3091The system sets limits on the amount of memory a process can have locked
3092and the amount of real memory it can have dedicated to it. @xref{Limits
3093on Resources}.
3094
3095In Linux, locked pages aren't as locked as you might think.
3096Two virtual pages that are not shared memory can nonetheless be backed
3097by the same real frame. The kernel does this in the name of efficiency
3098when it knows both virtual pages contain identical data, and does it
68979757 3099even if one or both of the virtual pages are locked.
99a20616
UD
3100
3101But when a process modifies one of those pages, the kernel must get it a
3102separate frame and fill it with the page's data. This is known as a
3103@dfn{copy-on-write page fault}. It takes a small amount of time and in
3104a pathological case, getting that frame may require I/O.
3105@cindex copy-on-write page fault
3106@cindex page fault, copy-on-write
3107
3108To make sure this doesn't happen to your program, don't just lock the
3109pages. Write to them as well, unless you know you won't write to them
3110ever. And to make sure you have pre-allocated frames for your stack,
3111enter a scope that declares a C automatic variable larger than the
3112maximum stack size you will need, set it to something, then return from
3113its scope.
3114
3115@node Page Lock Functions
3116@subsection Functions To Lock And Unlock Pages
3117
3118The symbols in this section are declared in @file{sys/mman.h}. These
3119functions are defined by POSIX.1b, but their availability depends on
3120your kernel. If your kernel doesn't allow these functions, they exist
3121but always fail. They @emph{are} available with a Linux kernel.
3122
3123@strong{Portability Note:} POSIX.1b requires that when the @code{mlock}
3124and @code{munlock} functions are available, the file @file{unistd.h}
3125define the macro @code{_POSIX_MEMLOCK_RANGE} and the file
3126@code{limits.h} define the macro @code{PAGESIZE} to be the size of a
3127memory page in bytes. It requires that when the @code{mlockall} and
3128@code{munlockall} functions are available, the @file{unistd.h} file
1f77f049 3129define the macro @code{_POSIX_MEMLOCK}. @Theglibc{} conforms to
99a20616
UD
3130this requirement.
3131
3132@comment sys/mman.h
3133@comment POSIX.1b
3134@deftypefun int mlock (const void *@var{addr}, size_t @var{len})
9f529d7c 3135@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
99a20616
UD
3136
3137@code{mlock} locks a range of the calling process' virtual pages.
3138
3139The range of memory starts at address @var{addr} and is @var{len} bytes
3140long. Actually, since you must lock whole pages, it is the range of
3141pages that include any part of the specified range.
3142
3143When the function returns successfully, each of those pages is backed by
3144(connected to) a real frame (is resident) and is marked to stay that
3145way. This means the function may cause page-ins and have to wait for
3146them.
3147
3148When the function fails, it does not affect the lock status of any
3149pages.
3150
3151The return value is zero if the function succeeds. Otherwise, it is
3152@code{-1} and @code{errno} is set accordingly. @code{errno} values
3153specific to this function are:
3154
3155@table @code
3156@item ENOMEM
3157@itemize @bullet
3158@item
3159At least some of the specified address range does not exist in the
3160calling process' virtual address space.
3161@item
3162The locking would cause the process to exceed its locked page limit.
3163@end itemize
3164
3165@item EPERM
3166The calling process is not superuser.
3167
3168@item EINVAL
3169@var{len} is not positive.
3170
3171@item ENOSYS
3172The kernel does not provide @code{mlock} capability.
3173
3174@end table
3175
3176You can lock @emph{all} a process' memory with @code{mlockall}. You
3177unlock memory with @code{munlock} or @code{munlockall}.
3178
3179To avoid all page faults in a C program, you have to use
3180@code{mlockall}, because some of the memory a program uses is hidden
3181from the C code, e.g. the stack and automatic variables, and you
3182wouldn't know what address to tell @code{mlock}.
3183
3184@end deftypefun
3185
3186@comment sys/mman.h
3187@comment POSIX.1b
3188@deftypefun int munlock (const void *@var{addr}, size_t @var{len})
9f529d7c 3189@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
99a20616 3190
10e0498e 3191@code{munlock} unlocks a range of the calling process' virtual pages.
99a20616
UD
3192
3193@code{munlock} is the inverse of @code{mlock} and functions completely
3194analogously to @code{mlock}, except that there is no @code{EPERM}
3195failure.
3196
3197@end deftypefun
3198
3199@comment sys/mman.h
3200@comment POSIX.1b
3201@deftypefun int mlockall (int @var{flags})
9f529d7c 3202@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
99a20616
UD
3203
3204@code{mlockall} locks all the pages in a process' virtual memory address
3205space, and/or any that are added to it in the future. This includes the
3206pages of the code, data and stack segment, as well as shared libraries,
3207user space kernel data, shared memory, and memory mapped files.
3208
3209@var{flags} is a string of single bit flags represented by the following
3210macros. They tell @code{mlockall} which of its functions you want. All
3211other bits must be zero.
3212
3213@table @code
3214
3215@item MCL_CURRENT
3216Lock all pages which currently exist in the calling process' virtual
3217address space.
3218
3219@item MCL_FUTURE
3220Set a mode such that any pages added to the process' virtual address
3221space in the future will be locked from birth. This mode does not
3222affect future address spaces owned by the same process so exec, which
3223replaces a process' address space, wipes out @code{MCL_FUTURE}.
3224@xref{Executing a File}.
3225
3226@end table
3227
3228When the function returns successfully, and you specified
3229@code{MCL_CURRENT}, all of the process' pages are backed by (connected
3230to) real frames (they are resident) and are marked to stay that way.
3231This means the function may cause page-ins and have to wait for them.
3232
3233When the process is in @code{MCL_FUTURE} mode because it successfully
3234executed this function and specified @code{MCL_CURRENT}, any system call
3235by the process that requires space be added to its virtual address space
3236fails with @code{errno} = @code{ENOMEM} if locking the additional space
3237would cause the process to exceed its locked page limit. In the case
0bc93a2f 3238that the address space addition that can't be accommodated is stack
99a20616
UD
3239expansion, the stack expansion fails and the kernel sends a
3240@code{SIGSEGV} signal to the process.
3241
3242When the function fails, it does not affect the lock status of any pages
3243or the future locking mode.
3244
3245The return value is zero if the function succeeds. Otherwise, it is
3246@code{-1} and @code{errno} is set accordingly. @code{errno} values
3247specific to this function are:
3248
3249@table @code
3250@item ENOMEM
3251@itemize @bullet
3252@item
3253At least some of the specified address range does not exist in the
3254calling process' virtual address space.
3255@item
3256The locking would cause the process to exceed its locked page limit.
3257@end itemize
3258
3259@item EPERM
3260The calling process is not superuser.
3261
3262@item EINVAL
3263Undefined bits in @var{flags} are not zero.
3264
3265@item ENOSYS
3266The kernel does not provide @code{mlockall} capability.
3267
3268@end table
3269
3270You can lock just specific pages with @code{mlock}. You unlock pages
3271with @code{munlockall} and @code{munlock}.
3272
3273@end deftypefun
3274
3275
3276@comment sys/mman.h
3277@comment POSIX.1b
3278@deftypefun int munlockall (void)
9f529d7c 3279@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
99a20616
UD
3280
3281@code{munlockall} unlocks every page in the calling process' virtual
3ef569c7 3282address space and turns off @code{MCL_FUTURE} future locking mode.
99a20616
UD
3283
3284The return value is zero if the function succeeds. Otherwise, it is
68979757 3285@code{-1} and @code{errno} is set accordingly. The only way this
99a20616
UD
3286function can fail is for generic reasons that all functions and system
3287calls can fail, so there are no specific @code{errno} values.
3288
3289@end deftypefun
3290
3291
3292
3293
a9ddb793
UD
3294@ignore
3295@c This was never actually implemented. -zw
28f540f4
RM
3296@node Relocating Allocator
3297@section Relocating Allocator
3298
3299@cindex relocating memory allocator
3300Any system of dynamic memory allocation has overhead: the amount of
3301space it uses is more than the amount the program asks for. The
3302@dfn{relocating memory allocator} achieves very low overhead by moving
3303blocks in memory as necessary, on its own initiative.
3304
a9ddb793
UD
3305@c @menu
3306@c * Relocator Concepts:: How to understand relocating allocation.
3307@c * Using Relocator:: Functions for relocating allocation.
3308@c @end menu
28f540f4
RM
3309
3310@node Relocator Concepts
3311@subsection Concepts of Relocating Allocation
3312
3313@ifinfo
3314The @dfn{relocating memory allocator} achieves very low overhead by
3315moving blocks in memory as necessary, on its own initiative.
3316@end ifinfo
3317
3318When you allocate a block with @code{malloc}, the address of the block
3319never changes unless you use @code{realloc} to change its size. Thus,
3320you can safely store the address in various places, temporarily or
3321permanently, as you like. This is not safe when you use the relocating
3322memory allocator, because any and all relocatable blocks can move
3323whenever you allocate memory in any fashion. Even calling @code{malloc}
3324or @code{realloc} can move the relocatable blocks.
3325
3326@cindex handle
3327For each relocatable block, you must make a @dfn{handle}---a pointer
3328object in memory, designated to store the address of that block. The
3329relocating allocator knows where each block's handle is, and updates the
3330address stored there whenever it moves the block, so that the handle
3331always points to the block. Each time you access the contents of the
3332block, you should fetch its address anew from the handle.
3333
3334To call any of the relocating allocator functions from a signal handler
3335is almost certainly incorrect, because the signal could happen at any
3336time and relocate all the blocks. The only way to make this safe is to
3337block the signal around any access to the contents of any relocatable
3338block---not a convenient mode of operation. @xref{Nonreentrancy}.
3339
3340@node Using Relocator
3341@subsection Allocating and Freeing Relocatable Blocks
3342
3343@pindex malloc.h
3344In the descriptions below, @var{handleptr} designates the address of the
3345handle. All the functions are declared in @file{malloc.h}; all are GNU
3346extensions.
3347
3348@comment malloc.h
3349@comment GNU
a9ddb793 3350@c @deftypefun {void *} r_alloc (void **@var{handleptr}, size_t @var{size})
28f540f4
RM
3351This function allocates a relocatable block of size @var{size}. It
3352stores the block's address in @code{*@var{handleptr}} and returns
3353a non-null pointer to indicate success.
3354
3355If @code{r_alloc} can't get the space needed, it stores a null pointer
3356in @code{*@var{handleptr}}, and returns a null pointer.
3357@end deftypefun
3358
3359@comment malloc.h
3360@comment GNU
a9ddb793 3361@c @deftypefun void r_alloc_free (void **@var{handleptr})
28f540f4
RM
3362This function is the way to free a relocatable block. It frees the
3363block that @code{*@var{handleptr}} points to, and stores a null pointer
3364in @code{*@var{handleptr}} to show it doesn't point to an allocated
3365block any more.
3366@end deftypefun
3367
3368@comment malloc.h
3369@comment GNU
a9ddb793 3370@c @deftypefun {void *} r_re_alloc (void **@var{handleptr}, size_t @var{size})
28f540f4
RM
3371The function @code{r_re_alloc} adjusts the size of the block that
3372@code{*@var{handleptr}} points to, making it @var{size} bytes long. It
3373stores the address of the resized block in @code{*@var{handleptr}} and
3374returns a non-null pointer to indicate success.
3375
3376If enough memory is not available, this function returns a null pointer
3377and does not modify @code{*@var{handleptr}}.
3378@end deftypefun
a9ddb793 3379@end ignore
28f540f4 3380
99a20616
UD
3381
3382
3383
c131718c
UD
3384@ignore
3385@comment No longer available...
3386
3387@comment @node Memory Warnings
3388@comment @section Memory Usage Warnings
3389@comment @cindex memory usage warnings
3390@comment @cindex warnings of memory almost full
28f540f4
RM
3391
3392@pindex malloc.c
3393You can ask for warnings as the program approaches running out of memory
3394space, by calling @code{memory_warnings}. This tells @code{malloc} to
3395check memory usage every time it asks for more memory from the operating
3396system. This is a GNU extension declared in @file{malloc.h}.
3397
3398@comment malloc.h
3399@comment GNU
c131718c 3400@comment @deftypefun void memory_warnings (void *@var{start}, void (*@var{warn-func}) (const char *))
28f540f4
RM
3401Call this function to request warnings for nearing exhaustion of virtual
3402memory.
3403
3404The argument @var{start} says where data space begins, in memory. The
3405allocator compares this against the last address used and against the
3406limit of data space, to determine the fraction of available memory in
3407use. If you supply zero for @var{start}, then a default value is used
3408which is right in most circumstances.
3409
3410For @var{warn-func}, supply a function that @code{malloc} can call to
3411warn you. It is called with a string (a warning message) as argument.
3412Normally it ought to display the string for the user to read.
3413@end deftypefun
3414
3415The warnings come when memory becomes 75% full, when it becomes 85%
3416full, and when it becomes 95% full. Above 95% you get another warning
3417each time memory usage increases.
c131718c
UD
3418
3419@end ignore