]> git.ipfire.org Git - thirdparty/glibc.git/blob - manual/memory.texi
manual/memory.texi: Bring aligned allocation docs up to date.
[thirdparty/glibc.git] / manual / memory.texi
1 @node Memory, Character Handling, Error Reporting, Top
2 @chapter Virtual Memory Allocation And Paging
3 @c %MENU% Allocating virtual memory and controlling paging
4 @cindex memory allocation
5 @cindex storage allocation
6
7 This chapter describes how processes manage and use memory in a system
8 that uses @theglibc{}.
9
10 @Theglibc{} has several functions for dynamically allocating
11 virtual memory in various ways. They vary in generality and in
12 efficiency. The library also provides functions for controlling paging
13 and allocation of real memory.
14
15
16 @menu
17 * Memory Concepts:: An introduction to concepts and terminology.
18 * Memory Allocation:: Allocating storage for your program data
19 * Resizing the Data Segment:: @code{brk}, @code{sbrk}
20 * Locking Pages:: Preventing page faults
21 @end menu
22
23 Memory 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
30 One of the most basic resources a process has available to it is memory.
31 There are a lot of different ways systems organize memory, but in a
32 typical one, each process has one linear virtual address space, with
33 addresses running from zero to some huge maximum. It need not be
34 contiguous; i.e., not all of these addresses actually can be used to
35 store data.
36
37 The virtual memory is divided into pages (4 kilobytes is typical).
38 Backing each page of virtual memory is a page of real memory (called a
39 @dfn{frame}) or some secondary storage, usually disk space. The disk
40 space might be swap space or just some ordinary disk file. Actually, a
41 page of all zeroes sometimes has nothing at all backing it -- there's
42 just a flag saying it is all zeroes.
43 @cindex page frame
44 @cindex frame, real memory
45 @cindex swap space
46 @cindex page, virtual memory
47
48 The same frame of real memory or backing store can back multiple virtual
49 pages belonging to multiple processes. This is normally the case, for
50 example, with virtual memory occupied by @glibcadj{} code. The same
51 real memory frame containing the @code{printf} function backs a virtual
52 memory page in each of the existing processes that has a @code{printf}
53 call in its program.
54
55 In order for a program to access any part of a virtual page, the page
56 must at that moment be backed by (``connected to'') a real frame. But
57 because there is usually a lot more virtual memory than real memory, the
58 pages must move back and forth between real memory and backing store
59 regularly, coming into real memory when a process needs to access them
60 and then retreating to backing store when not needed anymore. This
61 movement is called @dfn{paging}.
62
63 When a program attempts to access a page which is not at that moment
64 backed by real memory, this is known as a @dfn{page fault}. When a page
65 fault occurs, the kernel suspends the process, places the page into a
66 real page frame (this is called ``paging in'' or ``faulting in''), then
67 resumes the process so that from the process' point of view, the page
68 was in real memory all along. In fact, to the process, all pages always
69 seem to be in real memory. Except for one thing: the elapsed execution
70 time of an instruction that would normally be a few nanoseconds is
71 suddenly much, much, longer (because the kernel normally has to do I/O
72 to complete the page-in). For programs sensitive to that, the functions
73 described in @ref{Locking Pages} can control it.
74 @cindex page fault
75 @cindex paging
76
77 Within each virtual address space, a process has to keep track of what
78 is at which addresses, and that process is called memory allocation.
79 Allocation usually brings to mind meting out scarce resources, but in
80 the case of virtual memory, that's not a major goal, because there is
81 generally much more of it than anyone needs. Memory allocation within a
82 process is mainly just a matter of making sure that the same byte of
83 memory isn't used to store two different things.
84
85 Processes allocate memory in two major ways: by exec and
86 programmatically. Actually, forking is a third way, but it's not very
87 interesting. @xref{Creating a Process}.
88
89 Exec is the operation of creating a virtual address space for a process,
90 loading its basic program into it, and executing the program. It is
91 done by the ``exec'' family of functions (e.g. @code{execl}). The
92 operation takes a program file (an executable), it allocates space to
93 load all the data in the executable, loads it, and transfers control to
94 it. That data is most notably the instructions of the program (the
95 @dfn{text}), but also literals and constants in the program and even
96 some variables: C variables with the static storage class (@pxref{Memory
97 Allocation and C}).
98 @cindex executable
99 @cindex literals
100 @cindex constants
101
102 Once that program begins to execute, it uses programmatic allocation to
103 gain additional memory. In a C program with @theglibc{}, there
104 are two kinds of programmatic allocation: automatic and dynamic.
105 @xref{Memory Allocation and C}.
106
107 Memory-mapped I/O is another form of dynamic virtual memory allocation.
108 Mapping memory to a file means declaring that the contents of certain
109 range of a process' addresses shall be identical to the contents of a
110 specified regular file. The system makes the virtual memory initially
111 contain the contents of the file, and if you modify the memory, the
112 system writes the same modification to the file. Note that due to the
113 magic of virtual memory and page faults, there is no reason for the
114 system to do I/O to read the file, or allocate real memory for its
115 contents, until the program accesses the virtual memory.
116 @xref{Memory-mapped I/O}.
117 @cindex memory mapped I/O
118 @cindex memory mapped file
119 @cindex files, accessing
120
121 Just as it programmatically allocates memory, the program can
122 programmatically deallocate (@dfn{free}) it. You can't free the memory
123 that was allocated by exec. When the program exits or execs, you might
124 say that all its memory gets freed, but since in both cases the address
125 space ceases to exist, the point is really moot. @xref{Program
126 Termination}.
127 @cindex execing a program
128 @cindex freeing memory
129 @cindex exiting a program
130
131 A process' virtual address space is divided into segments. A segment is
132 a contiguous range of virtual addresses. Three important segments are:
133
134 @itemize @bullet
135
136 @item
137
138 The @dfn{text segment} contains a program's instructions and literals and
139 static constants. It is allocated by exec and stays the same size for
140 the life of the virtual address space.
141
142 @item
143 The @dfn{data segment} is working storage for the program. It can be
144 preallocated and preloaded by exec and the process can extend or shrink
145 it by calling functions as described in @xref{Resizing the Data
146 Segment}. Its lower end is fixed.
147
148 @item
149 The @dfn{stack segment} contains a program stack. It grows as the stack
150 grows, but doesn't shrink when the stack shrinks.
151
152 @end itemize
153
154
155
156 @node Memory Allocation
157 @section Allocating Storage For Program Data
158
159 This section covers how ordinary programs manage storage for their data,
160 including the famous @code{malloc} function and some fancier facilities
161 special @theglibc{} and GNU Compiler.
162
163 @menu
164 * Memory Allocation and C:: How to get different kinds of allocation in C.
165 * Unconstrained Allocation:: The @code{malloc} facility allows fully general
166 dynamic allocation.
167 * Allocation Debugging:: Finding memory leaks and not freed memory.
168 * Obstacks:: Obstacks are less general than malloc
169 but more efficient and convenient.
170 * Variable Size Automatic:: Allocation of variable-sized blocks
171 of automatic storage that are freed when the
172 calling function returns.
173 @end menu
174
175
176 @node Memory Allocation and C
177 @subsection Memory Allocation in C Programs
178
179 The C language supports two kinds of memory allocation through the
180 variables in C programs:
181
182 @itemize @bullet
183 @item
184 @dfn{Static allocation} is what happens when you declare a static or
185 global variable. Each static or global variable defines one block of
186 space, of a fixed size. The space is allocated once, when your program
187 is started (part of the exec operation), and is never freed.
188 @cindex static memory allocation
189 @cindex static storage class
190
191 @item
192 @dfn{Automatic allocation} happens when you declare an automatic
193 variable, such as a function argument or a local variable. The space
194 for an automatic variable is allocated when the compound statement
195 containing the declaration is entered, and is freed when that
196 compound statement is exited.
197 @cindex automatic memory allocation
198 @cindex automatic storage class
199
200 In GNU C, the size of the automatic storage can be an expression
201 that varies. In other C implementations, it must be a constant.
202 @end itemize
203
204 A third important kind of memory allocation, @dfn{dynamic allocation},
205 is not supported by C variables but is available via @glibcadj{}
206 functions.
207 @cindex dynamic memory allocation
208
209 @subsubsection Dynamic Memory Allocation
210 @cindex dynamic memory allocation
211
212 @dfn{Dynamic memory allocation} is a technique in which programs
213 determine as they are running where to store some information. You need
214 dynamic allocation when the amount of memory you need, or how long you
215 continue to need it, depends on factors that are not known before the
216 program runs.
217
218 For example, you may need a block to store a line read from an input
219 file; since there is no limit to how long a line can be, you must
220 allocate the memory dynamically and make it dynamically larger as you
221 read more of the line.
222
223 Or, you may need a block for each record or each definition in the input
224 data; since you can't know in advance how many there will be, you must
225 allocate a new block for each record or definition as you read it.
226
227 When you use dynamic allocation, the allocation of a block of memory is
228 an action that the program requests explicitly. You call a function or
229 macro when you want to allocate space, and specify the size with an
230 argument. If you want to free the space, you do so by calling another
231 function or macro. You can do these things whenever you want, as often
232 as you want.
233
234 Dynamic allocation is not supported by C variables; there is no storage
235 class ``dynamic'', and there can never be a C variable whose value is
236 stored in dynamically allocated space. The only way to get dynamically
237 allocated memory is via a system call (which is generally via a @glibcadj{}
238 function call), and the only way to refer to dynamically
239 allocated space is through a pointer. Because it is less convenient,
240 and because the actual process of dynamic allocation requires more
241 computation time, programmers generally use dynamic allocation only when
242 neither static nor automatic allocation will serve.
243
244 For example, if you want to allocate dynamically some space to hold a
245 @code{struct foobar}, you cannot declare a variable of type @code{struct
246 foobar} whose contents are the dynamically allocated space. But you can
247 declare a variable of pointer type @code{struct foobar *} and assign it the
248 address of the space. Then you can use the operators @samp{*} and
249 @samp{->} on this pointer variable to refer to the contents of the space:
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
262 @subsection Unconstrained Allocation
263 @cindex unconstrained memory allocation
264 @cindex @code{malloc} function
265 @cindex heap, dynamic allocation from
266
267 The most general dynamic allocation facility is @code{malloc}. It
268 allows you to allocate blocks of memory of any size at any time, make
269 them bigger or smaller at any time, and free the blocks individually at
270 any time (or never).
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.
283 * Aligned Memory Blocks:: Allocating specially aligned memory.
284 * Malloc Tunable Parameters:: Use @code{mallopt} to adjust allocation
285 parameters.
286 * Heap Consistency Checking:: Automatic checking for errors.
287 * Hooks for Malloc:: You can use these hooks for debugging
288 programs that use @code{malloc}.
289 * Statistics of Malloc:: Getting information about how much
290 memory your program is using.
291 * Summary of Malloc:: Summary of @code{malloc} and related functions.
292 @end menu
293
294 @node Basic Allocation
295 @subsubsection Basic Memory Allocation
296 @cindex allocation of memory with @code{malloc}
297
298 To allocate a block of memory, call @code{malloc}. The prototype for
299 this function is in @file{stdlib.h}.
300 @pindex stdlib.h
301
302 @comment malloc.h stdlib.h
303 @comment ISO
304 @deftypefun {void *} malloc (size_t @var{size})
305 This function returns a pointer to a newly allocated block @var{size}
306 bytes long, or a null pointer if the block could not be allocated.
307 @end deftypefun
308
309 The contents of the block are undefined; you must initialize it yourself
310 (or use @code{calloc} instead; @pxref{Allocating Cleared Space}).
311 Normally you would cast the value as a pointer to the kind of object
312 that you want to store in the block. Here we show an example of doing
313 so, and of initializing the space with zeros using the library function
314 @code{memset} (@pxref{Copying and Concatenation}):
315
316 @smallexample
317 struct foo *ptr;
318 @dots{}
319 ptr = (struct foo *) malloc (sizeof (struct foo));
320 if (ptr == 0) abort ();
321 memset (ptr, 0, sizeof (struct foo));
322 @end smallexample
323
324 You can store the result of @code{malloc} into any pointer variable
325 without a cast, because @w{ISO C} automatically converts the type
326 @code{void *} to another type of pointer when necessary. But the cast
327 is necessary in contexts other than assignment operators or if you might
328 want your code to run in traditional C.
329
330 Remember that when allocating space for a string, the argument to
331 @code{malloc} must be one plus the length of the string. This is
332 because a string is terminated with a null character that doesn't count
333 in the ``length'' of the string but does need space. For example:
334
335 @smallexample
336 char *ptr;
337 @dots{}
338 ptr = (char *) malloc (length + 1);
339 @end smallexample
340
341 @noindent
342 @xref{Representation of Strings}, for more information about this.
343
344 @node Malloc Examples
345 @subsubsection Examples of @code{malloc}
346
347 If no more space is available, @code{malloc} returns a null pointer.
348 You should check the value of @emph{every} call to @code{malloc}. It is
349 useful to write a subroutine that calls @code{malloc} and reports an
350 error if the value is a null pointer, returning only if the value is
351 nonzero. This function is conventionally called @code{xmalloc}. Here
352 it is:
353
354 @smallexample
355 void *
356 xmalloc (size_t size)
357 @{
358 void *value = malloc (size);
359 if (value == 0)
360 fatal ("virtual memory exhausted");
361 return value;
362 @}
363 @end smallexample
364
365 Here is a real example of using @code{malloc} (by way of @code{xmalloc}).
366 The function @code{savestring} will copy a sequence of characters into
367 a newly allocated null-terminated string:
368
369 @smallexample
370 @group
371 char *
372 savestring (const char *ptr, size_t len)
373 @{
374 char *value = (char *) xmalloc (len + 1);
375 value[len] = '\0';
376 return (char *) memcpy (value, ptr, len);
377 @}
378 @end group
379 @end smallexample
380
381 The block that @code{malloc} gives you is guaranteed to be aligned so
382 that it can hold any type of data. On @gnusystems{}, the address is
383 always a multiple of eight on 32-bit systems, and a multiple of 16 on
384 64-bit systems. Only rarely is any higher boundary (such as a page
385 boundary) necessary; for those cases, use @code{posix_memalign}
386 (@pxref{Aligned Memory Blocks}).
387
388 Note that the memory located after the end of the block is likely to be
389 in use for something else; perhaps a block already allocated by another
390 call to @code{malloc}. If you attempt to treat the block as longer than
391 you asked for it to be, you are liable to destroy the data that
392 @code{malloc} uses to keep track of its blocks, or you may destroy the
393 contents of another block. If you have already allocated a block and
394 discover you want it to be bigger, use @code{realloc} (@pxref{Changing
395 Block Size}).
396
397 @node Freeing after Malloc
398 @subsubsection Freeing Memory Allocated with @code{malloc}
399 @cindex freeing memory allocated with @code{malloc}
400 @cindex heap, freeing memory from
401
402 When you no longer need a block that you got with @code{malloc}, use the
403 function @code{free} to make the block available to be allocated again.
404 The prototype for this function is in @file{stdlib.h}.
405 @pindex stdlib.h
406
407 @comment malloc.h stdlib.h
408 @comment ISO
409 @deftypefun void free (void *@var{ptr})
410 The @code{free} function deallocates the block of memory pointed at
411 by @var{ptr}.
412 @end deftypefun
413
414 @comment stdlib.h
415 @comment Sun
416 @deftypefun void cfree (void *@var{ptr})
417 This function does the same thing as @code{free}. It's provided for
418 backward compatibility with SunOS; you should use @code{free} instead.
419 @end deftypefun
420
421 Freeing a block alters the contents of the block. @strong{Do not expect to
422 find any data (such as a pointer to the next block in a chain of blocks) in
423 the block after freeing it.} Copy whatever you need out of the block before
424 freeing it! Here is an example of the proper way to free all the blocks in
425 a chain, and the strings that they point to:
426
427 @smallexample
428 struct chain
429 @{
430 struct chain *next;
431 char *name;
432 @}
433
434 void
435 free_chain (struct chain *chain)
436 @{
437 while (chain != 0)
438 @{
439 struct chain *next = chain->next;
440 free (chain->name);
441 free (chain);
442 chain = next;
443 @}
444 @}
445 @end smallexample
446
447 Occasionally, @code{free} can actually return memory to the operating
448 system and make the process smaller. Usually, all it can do is allow a
449 later call to @code{malloc} to reuse the space. In the meantime, the
450 space remains in your program as part of a free-list used internally by
451 @code{malloc}.
452
453 There is no point in freeing blocks at the end of a program, because all
454 of the program's space is given back to the system when the process
455 terminates.
456
457 @node Changing Block Size
458 @subsubsection Changing the Size of a Block
459 @cindex changing the size of a block (@code{malloc})
460
461 Often you do not know for certain how big a block you will ultimately need
462 at the time you must begin to use the block. For example, the block might
463 be a buffer that you use to hold a line being read from a file; no matter
464 how long you make the buffer initially, you may encounter a line that is
465 longer.
466
467 You can make the block longer by calling @code{realloc}. This function
468 is declared in @file{stdlib.h}.
469 @pindex stdlib.h
470
471 @comment malloc.h stdlib.h
472 @comment ISO
473 @deftypefun {void *} realloc (void *@var{ptr}, size_t @var{newsize})
474 The @code{realloc} function changes the size of the block whose address is
475 @var{ptr} to be @var{newsize}.
476
477 Since the space after the end of the block may be in use, @code{realloc}
478 may find it necessary to copy the block to a new address where more free
479 space is available. The value of @code{realloc} is the new address of the
480 block. If the block needs to be moved, @code{realloc} copies the old
481 contents.
482
483 If you pass a null pointer for @var{ptr}, @code{realloc} behaves just
484 like @samp{malloc (@var{newsize})}. This can be convenient, but beware
485 that older implementations (before @w{ISO C}) may not support this
486 behavior, and will probably crash when @code{realloc} is passed a null
487 pointer.
488 @end deftypefun
489
490 Like @code{malloc}, @code{realloc} may return a null pointer if no
491 memory space is available to make the block bigger. When this happens,
492 the original block is untouched; it has not been modified or relocated.
493
494 In most cases it makes no difference what happens to the original block
495 when @code{realloc} fails, because the application program cannot continue
496 when it is out of memory, and the only thing to do is to give a fatal error
497 message. Often it is convenient to write and use a subroutine,
498 conventionally called @code{xrealloc}, that takes care of the error message
499 as @code{xmalloc} does for @code{malloc}:
500
501 @smallexample
502 void *
503 xrealloc (void *ptr, size_t size)
504 @{
505 void *value = realloc (ptr, size);
506 if (value == 0)
507 fatal ("Virtual memory exhausted");
508 return value;
509 @}
510 @end smallexample
511
512 You can also use @code{realloc} to make a block smaller. The reason you
513 would do this is to avoid tying up a lot of memory space when only a little
514 is needed.
515 @comment The following is no longer true with the new malloc.
516 @comment But it seems wise to keep the warning for other implementations.
517 In several allocation implementations, making a block smaller sometimes
518 necessitates copying it, so it can fail if no other space is available.
519
520 If the new size you specify is the same as the old size, @code{realloc}
521 is guaranteed to change nothing and return the same address that you gave.
522
523 @node Allocating Cleared Space
524 @subsubsection Allocating Cleared Space
525
526 The function @code{calloc} allocates memory and clears it to zero. It
527 is declared in @file{stdlib.h}.
528 @pindex stdlib.h
529
530 @comment malloc.h stdlib.h
531 @comment ISO
532 @deftypefun {void *} calloc (size_t @var{count}, size_t @var{eltsize})
533 This function allocates a block long enough to contain a vector of
534 @var{count} elements, each of size @var{eltsize}. Its contents are
535 cleared to zero before @code{calloc} returns.
536 @end deftypefun
537
538 You could define @code{calloc} as follows:
539
540 @smallexample
541 void *
542 calloc (size_t count, size_t eltsize)
543 @{
544 size_t size = count * eltsize;
545 void *value = malloc (size);
546 if (value != 0)
547 memset (value, 0, size);
548 return value;
549 @}
550 @end smallexample
551
552 But in general, it is not guaranteed that @code{calloc} calls
553 @code{malloc} internally. Therefore, if an application provides its own
554 @code{malloc}/@code{realloc}/@code{free} outside the C library, it
555 should always define @code{calloc}, too.
556
557 @node Efficiency and Malloc
558 @subsubsection Efficiency Considerations for @code{malloc}
559 @cindex efficiency and @code{malloc}
560
561
562
563
564 @ignore
565
566 @c No longer true, see below instead.
567 To make the best use of @code{malloc}, it helps to know that the GNU
568 version of @code{malloc} always dispenses small amounts of memory in
569 blocks whose sizes are powers of two. It keeps separate pools for each
570 power of two. This holds for sizes up to a page size. Therefore, if
571 you are free to choose the size of a small block in order to make
572 @code{malloc} more efficient, make it a power of two.
573 @c !!! xref getpagesize
574
575 Once a page is split up for a particular block size, it can't be reused
576 for another size unless all the blocks in it are freed. In many
577 programs, this is unlikely to happen. Thus, you can sometimes make a
578 program use memory more efficiently by using blocks of the same size for
579 many different purposes.
580
581 When you ask for memory blocks of a page or larger, @code{malloc} uses a
582 different strategy; it rounds the size up to a multiple of a page, and
583 it can coalesce and split blocks as needed.
584
585 The reason for the two strategies is that it is important to allocate
586 and free small blocks as fast as possible, but speed is less important
587 for a large block since the program normally spends a fair amount of
588 time using it. Also, large blocks are normally fewer in number.
589 Therefore, for large blocks, it makes sense to use a method which takes
590 more time to minimize the wasted space.
591
592 @end ignore
593
594 As opposed to other versions, the @code{malloc} in @theglibc{}
595 does not round up block sizes to powers of two, neither for large nor
596 for small sizes. Neighboring chunks can be coalesced on a @code{free}
597 no matter what their size is. This makes the implementation suitable
598 for all kinds of allocation patterns without generally incurring high
599 memory waste through fragmentation.
600
601 Very large blocks (much larger than a page) are allocated with
602 @code{mmap} (anonymous or via @code{/dev/zero}) by this implementation.
603 This has the great advantage that these chunks are returned to the
604 system immediately when they are freed. Therefore, it cannot happen
605 that a large chunk becomes ``locked'' in between smaller ones and even
606 after calling @code{free} wastes memory. The size threshold for
607 @code{mmap} to be used can be adjusted with @code{mallopt}. The use of
608 @code{mmap} can also be disabled completely.
609
610 @node Aligned Memory Blocks
611 @subsubsection Allocating Aligned Memory Blocks
612
613 @cindex page boundary
614 @cindex alignment (with @code{malloc})
615 @pindex stdlib.h
616 The address of a block returned by @code{malloc} or @code{realloc} in
617 @gnusystems{} is always a multiple of eight (or sixteen on 64-bit
618 systems). If you need a block whose address is a multiple of a higher
619 power of two than that, use @code{posix_memalign}. @code{posix_memalign}
620 is declared in @file{stdlib.h}.
621
622 @comment malloc.h
623 @comment BSD
624 @deftypefun {void *} memalign (size_t @var{boundary}, size_t @var{size})
625 The @code{memalign} function allocates a block of @var{size} bytes whose
626 address is a multiple of @var{boundary}. The @var{boundary} must be a
627 power of two! The function @code{memalign} works by allocating a
628 somewhat larger block, and then returning an address within the block
629 that is on the specified boundary.
630
631 The @code{memalign} function returns a null pointer on error and sets
632 @code{errno} to one of the following values:
633
634 @table @code
635 @item ENOMEM
636 There was insufficient memory available to satisfy the request.
637
638 @item EINVAL
639 @var{alignment} is not a power of two.
640
641 @end table
642
643 The @code{memalign} function is obsolete and @code{posix_memalign} should
644 be used instead.
645 @end deftypefun
646
647 @comment stdlib.h
648 @comment POSIX
649 @deftypefun int posix_memalign (void **@var{memptr}, size_t @var{alignment}, size_t @var{size})
650 The @code{posix_memalign} function is similar to the @code{memalign}
651 function in that it returns a buffer of @var{size} bytes aligned to a
652 multiple of @var{alignment}. But it adds one requirement to the
653 parameter @var{alignment}: the value must be a power of two multiple of
654 @code{sizeof (void *)}.
655
656 If the function succeeds in allocation memory a pointer to the allocated
657 memory is returned in @code{*@var{memptr}} and the return value is zero.
658 Otherwise the function returns an error value indicating the problem.
659 The possible error values returned are:
660
661 @table @code
662 @item ENOMEM
663 There was insufficient memory available to satisfy the request.
664
665 @item EINVAL
666 @var{alignment} is not a power of two multiple of @code{sizeof (void *)}.
667
668 @end table
669
670 This function was introduced in POSIX 1003.1d.
671 @end deftypefun
672
673 @comment malloc.h stdlib.h
674 @comment BSD
675 @deftypefun {void *} valloc (size_t @var{size})
676 Using @code{valloc} is like using @code{memalign} and passing the page size
677 as the value of the second argument. It is implemented like this:
678
679 @smallexample
680 void *
681 valloc (size_t size)
682 @{
683 return memalign (getpagesize (), size);
684 @}
685 @end smallexample
686
687 @ref{Query Memory Parameters} for more information about the memory
688 subsystem.
689
690 The @code{valloc} function is obsolete and @code{posix_memalign} should
691 be used instead.
692 @end deftypefun
693
694 @node Malloc Tunable Parameters
695 @subsubsection Malloc Tunable Parameters
696
697 You can adjust some parameters for dynamic memory allocation with the
698 @code{mallopt} function. This function is the general SVID/XPG
699 interface, defined in @file{malloc.h}.
700 @pindex malloc.h
701
702 @deftypefun int mallopt (int @var{param}, int @var{value})
703 When calling @code{mallopt}, the @var{param} argument specifies the
704 parameter to be set, and @var{value} the new value to be set. Possible
705 choices for @var{param}, as defined in @file{malloc.h}, are:
706
707 @table @code
708 @comment TODO: @item M_ARENA_MAX
709 @comment - Document ARENA_MAX env var.
710 @comment TODO: @item M_ARENA_TEST
711 @comment - Document ARENA_TEST env var.
712 @comment TODO: @item M_CHECK_ACTION
713 @item M_MMAP_MAX
714 The maximum number of chunks to allocate with @code{mmap}. Setting this
715 to zero disables all use of @code{mmap}.
716 @item M_MMAP_THRESHOLD
717 All chunks larger than this value are allocated outside the normal
718 heap, using the @code{mmap} system call. This way it is guaranteed
719 that the memory for these chunks can be returned to the system on
720 @code{free}. Note that requests smaller than this threshold might still
721 be allocated via @code{mmap}.
722 @comment TODO: @item M_MXFAST
723 @item M_PERTURB
724 If non-zero, memory blocks are filled with values depending on some
725 low order bits of this parameter when they are allocated (except when
726 allocated by @code{calloc}) and freed. This can be used to debug the
727 use of uninitialized or freed heap memory. Note that this option does not
728 guarantee that the freed block will have any specific values. It only
729 guarantees that the content the block had before it was freed will be
730 overwritten.
731 @item M_TOP_PAD
732 This parameter determines the amount of extra memory to obtain from the
733 system when a call to @code{sbrk} is required. It also specifies the
734 number of bytes to retain when shrinking the heap by calling @code{sbrk}
735 with a negative argument. This provides the necessary hysteresis in
736 heap size such that excessive amounts of system calls can be avoided.
737 @item M_TRIM_THRESHOLD
738 This is the minimum size (in bytes) of the top-most, releasable chunk
739 that will cause @code{sbrk} to be called with a negative argument in
740 order to return memory to the system.
741 @end table
742
743 @end deftypefun
744
745 @node Heap Consistency Checking
746 @subsubsection Heap Consistency Checking
747
748 @cindex heap consistency checking
749 @cindex consistency checking, of heap
750
751 You can ask @code{malloc} to check the consistency of dynamic memory by
752 using the @code{mcheck} function. This function is a GNU extension,
753 declared in @file{mcheck.h}.
754 @pindex mcheck.h
755
756 @comment mcheck.h
757 @comment GNU
758 @deftypefun int mcheck (void (*@var{abortfn}) (enum mcheck_status @var{status}))
759 Calling @code{mcheck} tells @code{malloc} to perform occasional
760 consistency checks. These will catch things such as writing
761 past the end of a block that was allocated with @code{malloc}.
762
763 The @var{abortfn} argument is the function to call when an inconsistency
764 is found. If you supply a null pointer, then @code{mcheck} uses a
765 default function which prints a message and calls @code{abort}
766 (@pxref{Aborting a Program}). The function you supply is called with
767 one argument, which says what sort of inconsistency was detected; its
768 type is described below.
769
770 It is too late to begin allocation checking once you have allocated
771 anything with @code{malloc}. So @code{mcheck} does nothing in that
772 case. The function returns @code{-1} if you call it too late, and
773 @code{0} otherwise (when it is successful).
774
775 The easiest way to arrange to call @code{mcheck} early enough is to use
776 the option @samp{-lmcheck} when you link your program; then you don't
777 need to modify your program source at all. Alternatively you might use
778 a debugger to insert a call to @code{mcheck} whenever the program is
779 started, for example these gdb commands will automatically call @code{mcheck}
780 whenever the program starts:
781
782 @smallexample
783 (gdb) break main
784 Breakpoint 1, main (argc=2, argv=0xbffff964) at whatever.c:10
785 (gdb) command 1
786 Type commands for when breakpoint 1 is hit, one per line.
787 End with a line saying just "end".
788 >call mcheck(0)
789 >continue
790 >end
791 (gdb) @dots{}
792 @end smallexample
793
794 This will however only work if no initialization function of any object
795 involved calls any of the @code{malloc} functions since @code{mcheck}
796 must be called before the first such function.
797
798 @end deftypefun
799
800 @deftypefun {enum mcheck_status} mprobe (void *@var{pointer})
801 The @code{mprobe} function lets you explicitly check for inconsistencies
802 in a particular allocated block. You must have already called
803 @code{mcheck} at the beginning of the program, to do its occasional
804 checks; calling @code{mprobe} requests an additional consistency check
805 to be done at the time of the call.
806
807 The argument @var{pointer} must be a pointer returned by @code{malloc}
808 or @code{realloc}. @code{mprobe} returns a value that says what
809 inconsistency, if any, was found. The values are described below.
810 @end deftypefun
811
812 @deftp {Data Type} {enum mcheck_status}
813 This enumerated type describes what kind of inconsistency was detected
814 in an allocated block, if any. Here are the possible values:
815
816 @table @code
817 @item MCHECK_DISABLED
818 @code{mcheck} was not called before the first allocation.
819 No consistency checking can be done.
820 @item MCHECK_OK
821 No inconsistency detected.
822 @item MCHECK_HEAD
823 The data immediately before the block was modified.
824 This commonly happens when an array index or pointer
825 is decremented too far.
826 @item MCHECK_TAIL
827 The data immediately after the block was modified.
828 This commonly happens when an array index or pointer
829 is incremented too far.
830 @item MCHECK_FREE
831 The block was already freed.
832 @end table
833 @end deftp
834
835 Another possibility to check for and guard against bugs in the use of
836 @code{malloc}, @code{realloc} and @code{free} is to set the environment
837 variable @code{MALLOC_CHECK_}. When @code{MALLOC_CHECK_} is set, a
838 special (less efficient) implementation is used which is designed to be
839 tolerant against simple errors, such as double calls of @code{free} with
840 the same argument, or overruns of a single byte (off-by-one bugs). Not
841 all such errors can be protected against, however, and memory leaks can
842 result. If @code{MALLOC_CHECK_} is set to @code{0}, any detected heap
843 corruption is silently ignored; if set to @code{1}, a diagnostic is
844 printed on @code{stderr}; if set to @code{2}, @code{abort} is called
845 immediately. This can be useful because otherwise a crash may happen
846 much later, and the true cause for the problem is then very hard to
847 track down.
848
849 There is one problem with @code{MALLOC_CHECK_}: in SUID or SGID binaries
850 it could possibly be exploited since diverging from the normal programs
851 behavior it now writes something to the standard error descriptor.
852 Therefore the use of @code{MALLOC_CHECK_} is disabled by default for
853 SUID and SGID binaries. It can be enabled again by the system
854 administrator by adding a file @file{/etc/suid-debug} (the content is
855 not important it could be empty).
856
857 So, what's the difference between using @code{MALLOC_CHECK_} and linking
858 with @samp{-lmcheck}? @code{MALLOC_CHECK_} is orthogonal with respect to
859 @samp{-lmcheck}. @samp{-lmcheck} has been added for backward
860 compatibility. Both @code{MALLOC_CHECK_} and @samp{-lmcheck} should
861 uncover the same bugs - but using @code{MALLOC_CHECK_} you don't need to
862 recompile your application.
863
864 @node Hooks for Malloc
865 @subsubsection Memory Allocation Hooks
866 @cindex allocation hooks, for @code{malloc}
867
868 @Theglibc{} lets you modify the behavior of @code{malloc},
869 @code{realloc}, and @code{free} by specifying appropriate hook
870 functions. You can use these hooks to help you debug programs that use
871 dynamic memory allocation, for example.
872
873 The hook variables are declared in @file{malloc.h}.
874 @pindex malloc.h
875
876 @comment malloc.h
877 @comment GNU
878 @defvar __malloc_hook
879 The value of this variable is a pointer to the function that
880 @code{malloc} uses whenever it is called. You should define this
881 function to look like @code{malloc}; that is, like:
882
883 @smallexample
884 void *@var{function} (size_t @var{size}, const void *@var{caller})
885 @end smallexample
886
887 The value of @var{caller} is the return address found on the stack when
888 the @code{malloc} function was called. This value allows you to trace
889 the memory consumption of the program.
890 @end defvar
891
892 @comment malloc.h
893 @comment GNU
894 @defvar __realloc_hook
895 The value of this variable is a pointer to function that @code{realloc}
896 uses whenever it is called. You should define this function to look
897 like @code{realloc}; that is, like:
898
899 @smallexample
900 void *@var{function} (void *@var{ptr}, size_t @var{size}, const void *@var{caller})
901 @end smallexample
902
903 The value of @var{caller} is the return address found on the stack when
904 the @code{realloc} function was called. This value allows you to trace the
905 memory consumption of the program.
906 @end defvar
907
908 @comment malloc.h
909 @comment GNU
910 @defvar __free_hook
911 The value of this variable is a pointer to function that @code{free}
912 uses whenever it is called. You should define this function to look
913 like @code{free}; that is, like:
914
915 @smallexample
916 void @var{function} (void *@var{ptr}, const void *@var{caller})
917 @end smallexample
918
919 The value of @var{caller} is the return address found on the stack when
920 the @code{free} function was called. This value allows you to trace the
921 memory consumption of the program.
922 @end defvar
923
924 @comment malloc.h
925 @comment GNU
926 @defvar __memalign_hook
927 The value of this variable is a pointer to function that @code{memalign},
928 @code{posix_memalign} and @code{valloc} use whenever they are called.
929 You should define this function to look like @code{memalign}; that is, like:
930
931 @smallexample
932 void *@var{function} (size_t @var{alignment}, size_t @var{size}, const void *@var{caller})
933 @end smallexample
934
935 The value of @var{caller} is the return address found on the stack when
936 the @code{memalign}, @code{posix_memalign} or @code{valloc} functions are
937 called. This value allows you to trace the memory consumption of the program.
938 @end defvar
939
940 You must make sure that the function you install as a hook for one of
941 these functions does not call that function recursively without restoring
942 the old value of the hook first! Otherwise, your program will get stuck
943 in an infinite recursion. Before calling the function recursively, one
944 should make sure to restore all the hooks to their previous value. When
945 coming back from the recursive call, all the hooks should be resaved
946 since a hook might modify itself.
947
948 @comment malloc.h
949 @comment GNU
950 @defvar __malloc_initialize_hook
951 The value of this variable is a pointer to a function that is called
952 once when the malloc implementation is initialized. This is a weak
953 variable, so it can be overridden in the application with a definition
954 like the following:
955
956 @smallexample
957 void (*@var{__malloc_initialize_hook}) (void) = my_init_hook;
958 @end smallexample
959 @end defvar
960
961 An issue to look out for is the time at which the malloc hook functions
962 can be safely installed. If the hook functions call the malloc-related
963 functions recursively, it is necessary that malloc has already properly
964 initialized itself at the time when @code{__malloc_hook} etc. is
965 assigned to. On the other hand, if the hook functions provide a
966 complete malloc implementation of their own, it is vital that the hooks
967 are assigned to @emph{before} the very first @code{malloc} call has
968 completed, because otherwise a chunk obtained from the ordinary,
969 un-hooked malloc may later be handed to @code{__free_hook}, for example.
970
971 In both cases, the problem can be solved by setting up the hooks from
972 within a user-defined function pointed to by
973 @code{__malloc_initialize_hook}---then the hooks will be set up safely
974 at the right time.
975
976 Here is an example showing how to use @code{__malloc_hook} and
977 @code{__free_hook} properly. It installs a function that prints out
978 information every time @code{malloc} or @code{free} is called. We just
979 assume here that @code{realloc} and @code{memalign} are not used in our
980 program.
981
982 @smallexample
983 /* Prototypes for __malloc_hook, __free_hook */
984 #include <malloc.h>
985
986 /* Prototypes for our hooks. */
987 static void my_init_hook (void);
988 static void *my_malloc_hook (size_t, const void *);
989 static void my_free_hook (void*, const void *);
990
991 /* Override initializing hook from the C library. */
992 void (*__malloc_initialize_hook) (void) = my_init_hook;
993
994 static void
995 my_init_hook (void)
996 @{
997 old_malloc_hook = __malloc_hook;
998 old_free_hook = __free_hook;
999 __malloc_hook = my_malloc_hook;
1000 __free_hook = my_free_hook;
1001 @}
1002
1003 static void *
1004 my_malloc_hook (size_t size, const void *caller)
1005 @{
1006 void *result;
1007 /* Restore all old hooks */
1008 __malloc_hook = old_malloc_hook;
1009 __free_hook = old_free_hook;
1010 /* Call recursively */
1011 result = malloc (size);
1012 /* Save underlying hooks */
1013 old_malloc_hook = __malloc_hook;
1014 old_free_hook = __free_hook;
1015 /* @r{@code{printf} might call @code{malloc}, so protect it too.} */
1016 printf ("malloc (%u) returns %p\n", (unsigned int) size, result);
1017 /* Restore our own hooks */
1018 __malloc_hook = my_malloc_hook;
1019 __free_hook = my_free_hook;
1020 return result;
1021 @}
1022
1023 static void
1024 my_free_hook (void *ptr, const void *caller)
1025 @{
1026 /* Restore all old hooks */
1027 __malloc_hook = old_malloc_hook;
1028 __free_hook = old_free_hook;
1029 /* Call recursively */
1030 free (ptr);
1031 /* Save underlying hooks */
1032 old_malloc_hook = __malloc_hook;
1033 old_free_hook = __free_hook;
1034 /* @r{@code{printf} might call @code{free}, so protect it too.} */
1035 printf ("freed pointer %p\n", ptr);
1036 /* Restore our own hooks */
1037 __malloc_hook = my_malloc_hook;
1038 __free_hook = my_free_hook;
1039 @}
1040
1041 main ()
1042 @{
1043 @dots{}
1044 @}
1045 @end smallexample
1046
1047 The @code{mcheck} function (@pxref{Heap Consistency Checking}) works by
1048 installing such hooks.
1049
1050 @c __morecore, __after_morecore_hook are undocumented
1051 @c It's not clear whether to document them.
1052
1053 @node Statistics of Malloc
1054 @subsubsection Statistics for Memory Allocation with @code{malloc}
1055
1056 @cindex allocation statistics
1057 You can get information about dynamic memory allocation by calling the
1058 @code{mallinfo} function. This function and its associated data type
1059 are declared in @file{malloc.h}; they are an extension of the standard
1060 SVID/XPG version.
1061 @pindex malloc.h
1062
1063 @comment malloc.h
1064 @comment GNU
1065 @deftp {Data Type} {struct mallinfo}
1066 This structure type is used to return information about the dynamic
1067 memory allocator. It contains the following members:
1068
1069 @table @code
1070 @item int arena
1071 This is the total size of memory allocated with @code{sbrk} by
1072 @code{malloc}, in bytes.
1073
1074 @item int ordblks
1075 This is the number of chunks not in use. (The memory allocator
1076 internally gets chunks of memory from the operating system, and then
1077 carves them up to satisfy individual @code{malloc} requests; see
1078 @ref{Efficiency and Malloc}.)
1079
1080 @item int smblks
1081 This field is unused.
1082
1083 @item int hblks
1084 This is the total number of chunks allocated with @code{mmap}.
1085
1086 @item int hblkhd
1087 This is the total size of memory allocated with @code{mmap}, in bytes.
1088
1089 @item int usmblks
1090 This field is unused.
1091
1092 @item int fsmblks
1093 This field is unused.
1094
1095 @item int uordblks
1096 This is the total size of memory occupied by chunks handed out by
1097 @code{malloc}.
1098
1099 @item int fordblks
1100 This is the total size of memory occupied by free (not in use) chunks.
1101
1102 @item int keepcost
1103 This is the size of the top-most releasable chunk that normally
1104 borders the end of the heap (i.e., the high end of the virtual address
1105 space's data segment).
1106
1107 @end table
1108 @end deftp
1109
1110 @comment malloc.h
1111 @comment SVID
1112 @deftypefun {struct mallinfo} mallinfo (void)
1113 This function returns information about the current dynamic memory usage
1114 in a structure of type @code{struct mallinfo}.
1115 @end deftypefun
1116
1117 @node Summary of Malloc
1118 @subsubsection Summary of @code{malloc}-Related Functions
1119
1120 Here is a summary of the functions that work with @code{malloc}:
1121
1122 @table @code
1123 @item void *malloc (size_t @var{size})
1124 Allocate a block of @var{size} bytes. @xref{Basic Allocation}.
1125
1126 @item void free (void *@var{addr})
1127 Free a block previously allocated by @code{malloc}. @xref{Freeing after
1128 Malloc}.
1129
1130 @item void *realloc (void *@var{addr}, size_t @var{size})
1131 Make a block previously allocated by @code{malloc} larger or smaller,
1132 possibly by copying it to a new location. @xref{Changing Block Size}.
1133
1134 @item void *calloc (size_t @var{count}, size_t @var{eltsize})
1135 Allocate a block of @var{count} * @var{eltsize} bytes using
1136 @code{malloc}, and set its contents to zero. @xref{Allocating Cleared
1137 Space}.
1138
1139 @item void *valloc (size_t @var{size})
1140 Allocate a block of @var{size} bytes, starting on a page boundary.
1141 @xref{Aligned Memory Blocks}.
1142
1143 @item int posix_memalign (void **@var{memptr}, size_t @var{alignment}, size_t @var{size})
1144 Allocate a block of @var{size} bytes, starting on an address that is a
1145 multiple of @var{alignment}. @xref{Aligned Memory Blocks}.
1146
1147 @item void *memalign (size_t @var{size}, size_t @var{boundary})
1148 Allocate a block of @var{size} bytes, starting on an address that is a
1149 multiple of @var{boundary}. @xref{Aligned Memory Blocks}.
1150
1151 @item int mallopt (int @var{param}, int @var{value})
1152 Adjust a tunable parameter. @xref{Malloc Tunable Parameters}.
1153
1154 @item int mcheck (void (*@var{abortfn}) (void))
1155 Tell @code{malloc} to perform occasional consistency checks on
1156 dynamically allocated memory, and to call @var{abortfn} when an
1157 inconsistency is found. @xref{Heap Consistency Checking}.
1158
1159 @item void *(*__malloc_hook) (size_t @var{size}, const void *@var{caller})
1160 A pointer to a function that @code{malloc} uses whenever it is called.
1161
1162 @item void *(*__realloc_hook) (void *@var{ptr}, size_t @var{size}, const void *@var{caller})
1163 A pointer to a function that @code{realloc} uses whenever it is called.
1164
1165 @item void (*__free_hook) (void *@var{ptr}, const void *@var{caller})
1166 A pointer to a function that @code{free} uses whenever it is called.
1167
1168 @item void (*__memalign_hook) (size_t @var{size}, size_t @var{alignment}, const void *@var{caller})
1169 A pointer to a function that @code{memalign}, @code{posix_memalign} and
1170 @code{valloc} use whenever they are called.
1171
1172 @item struct mallinfo mallinfo (void)
1173 Return information about the current dynamic memory usage.
1174 @xref{Statistics of Malloc}.
1175 @end table
1176
1177 @node Allocation Debugging
1178 @subsection Allocation Debugging
1179 @cindex allocation debugging
1180 @cindex malloc debugger
1181
1182 A complicated task when programming with languages which do not use
1183 garbage collected dynamic memory allocation is to find memory leaks.
1184 Long running programs must assure that dynamically allocated objects are
1185 freed at the end of their lifetime. If this does not happen the system
1186 runs out of memory, sooner or later.
1187
1188 The @code{malloc} implementation in @theglibc{} provides some
1189 simple means to detect such leaks and obtain some information to find
1190 the location. To do this the application must be started in a special
1191 mode which is enabled by an environment variable. There are no speed
1192 penalties for the program if the debugging mode is not enabled.
1193
1194 @menu
1195 * Tracing malloc:: How to install the tracing functionality.
1196 * Using the Memory Debugger:: Example programs excerpts.
1197 * Tips for the Memory Debugger:: Some more or less clever ideas.
1198 * Interpreting the traces:: What do all these lines mean?
1199 @end menu
1200
1201 @node Tracing malloc
1202 @subsubsection How to install the tracing functionality
1203
1204 @comment mcheck.h
1205 @comment GNU
1206 @deftypefun void mtrace (void)
1207 When the @code{mtrace} function is called it looks for an environment
1208 variable named @code{MALLOC_TRACE}. This variable is supposed to
1209 contain a valid file name. The user must have write access. If the
1210 file already exists it is truncated. If the environment variable is not
1211 set or it does not name a valid file which can be opened for writing
1212 nothing is done. The behavior of @code{malloc} etc. is not changed.
1213 For obvious reasons this also happens if the application is installed
1214 with the SUID or SGID bit set.
1215
1216 If the named file is successfully opened, @code{mtrace} installs special
1217 handlers for the functions @code{malloc}, @code{realloc}, and
1218 @code{free} (@pxref{Hooks for Malloc}). From then on, all uses of these
1219 functions are traced and protocolled into the file. There is now of
1220 course a speed penalty for all calls to the traced functions so tracing
1221 should not be enabled during normal use.
1222
1223 This function is a GNU extension and generally not available on other
1224 systems. The prototype can be found in @file{mcheck.h}.
1225 @end deftypefun
1226
1227 @comment mcheck.h
1228 @comment GNU
1229 @deftypefun void muntrace (void)
1230 The @code{muntrace} function can be called after @code{mtrace} was used
1231 to enable tracing the @code{malloc} calls. If no (successful) call of
1232 @code{mtrace} was made @code{muntrace} does nothing.
1233
1234 Otherwise it deinstalls the handlers for @code{malloc}, @code{realloc},
1235 and @code{free} and then closes the protocol file. No calls are
1236 protocolled anymore and the program runs again at full speed.
1237
1238 This function is a GNU extension and generally not available on other
1239 systems. The prototype can be found in @file{mcheck.h}.
1240 @end deftypefun
1241
1242 @node Using the Memory Debugger
1243 @subsubsection Example program excerpts
1244
1245 Even though the tracing functionality does not influence the runtime
1246 behavior of the program it is not a good idea to call @code{mtrace} in
1247 all programs. Just imagine that you debug a program using @code{mtrace}
1248 and all other programs used in the debugging session also trace their
1249 @code{malloc} calls. The output file would be the same for all programs
1250 and thus is unusable. Therefore one should call @code{mtrace} only if
1251 compiled for debugging. A program could therefore start like this:
1252
1253 @example
1254 #include <mcheck.h>
1255
1256 int
1257 main (int argc, char *argv[])
1258 @{
1259 #ifdef DEBUGGING
1260 mtrace ();
1261 #endif
1262 @dots{}
1263 @}
1264 @end example
1265
1266 This is all what is needed if you want to trace the calls during the
1267 whole runtime of the program. Alternatively you can stop the tracing at
1268 any time with a call to @code{muntrace}. It is even possible to restart
1269 the tracing again with a new call to @code{mtrace}. But this can cause
1270 unreliable results since there may be calls of the functions which are
1271 not called. Please note that not only the application uses the traced
1272 functions, also libraries (including the C library itself) use these
1273 functions.
1274
1275 This last point is also why it is no good idea to call @code{muntrace}
1276 before the program terminated. The libraries are informed about the
1277 termination of the program only after the program returns from
1278 @code{main} or calls @code{exit} and so cannot free the memory they use
1279 before this time.
1280
1281 So the best thing one can do is to call @code{mtrace} as the very first
1282 function in the program and never call @code{muntrace}. So the program
1283 traces almost all uses of the @code{malloc} functions (except those
1284 calls which are executed by constructors of the program or used
1285 libraries).
1286
1287 @node Tips for the Memory Debugger
1288 @subsubsection Some more or less clever ideas
1289
1290 You know the situation. The program is prepared for debugging and in
1291 all debugging sessions it runs well. But once it is started without
1292 debugging the error shows up. A typical example is a memory leak that
1293 becomes visible only when we turn off the debugging. If you foresee
1294 such situations you can still win. Simply use something equivalent to
1295 the following little program:
1296
1297 @example
1298 #include <mcheck.h>
1299 #include <signal.h>
1300
1301 static void
1302 enable (int sig)
1303 @{
1304 mtrace ();
1305 signal (SIGUSR1, enable);
1306 @}
1307
1308 static void
1309 disable (int sig)
1310 @{
1311 muntrace ();
1312 signal (SIGUSR2, disable);
1313 @}
1314
1315 int
1316 main (int argc, char *argv[])
1317 @{
1318 @dots{}
1319
1320 signal (SIGUSR1, enable);
1321 signal (SIGUSR2, disable);
1322
1323 @dots{}
1324 @}
1325 @end example
1326
1327 I.e., the user can start the memory debugger any time s/he wants if the
1328 program was started with @code{MALLOC_TRACE} set in the environment.
1329 The output will of course not show the allocations which happened before
1330 the first signal but if there is a memory leak this will show up
1331 nevertheless.
1332
1333 @node Interpreting the traces
1334 @subsubsection Interpreting the traces
1335
1336 If you take a look at the output it will look similar to this:
1337
1338 @example
1339 = Start
1340 @ [0x8048209] - 0x8064cc8
1341 @ [0x8048209] - 0x8064ce0
1342 @ [0x8048209] - 0x8064cf8
1343 @ [0x80481eb] + 0x8064c48 0x14
1344 @ [0x80481eb] + 0x8064c60 0x14
1345 @ [0x80481eb] + 0x8064c78 0x14
1346 @ [0x80481eb] + 0x8064c90 0x14
1347 = End
1348 @end example
1349
1350 What this all means is not really important since the trace file is not
1351 meant to be read by a human. Therefore no attention is given to
1352 readability. Instead there is a program which comes with @theglibc{}
1353 which interprets the traces and outputs a summary in an
1354 user-friendly way. The program is called @code{mtrace} (it is in fact a
1355 Perl script) and it takes one or two arguments. In any case the name of
1356 the file with the trace output must be specified. If an optional
1357 argument precedes the name of the trace file this must be the name of
1358 the program which generated the trace.
1359
1360 @example
1361 drepper$ mtrace tst-mtrace log
1362 No memory leaks.
1363 @end example
1364
1365 In this case the program @code{tst-mtrace} was run and it produced a
1366 trace file @file{log}. The message printed by @code{mtrace} shows there
1367 are no problems with the code, all allocated memory was freed
1368 afterwards.
1369
1370 If we call @code{mtrace} on the example trace given above we would get a
1371 different outout:
1372
1373 @example
1374 drepper$ mtrace errlog
1375 - 0x08064cc8 Free 2 was never alloc'd 0x8048209
1376 - 0x08064ce0 Free 3 was never alloc'd 0x8048209
1377 - 0x08064cf8 Free 4 was never alloc'd 0x8048209
1378
1379 Memory not freed:
1380 -----------------
1381 Address Size Caller
1382 0x08064c48 0x14 at 0x80481eb
1383 0x08064c60 0x14 at 0x80481eb
1384 0x08064c78 0x14 at 0x80481eb
1385 0x08064c90 0x14 at 0x80481eb
1386 @end example
1387
1388 We have called @code{mtrace} with only one argument and so the script
1389 has no chance to find out what is meant with the addresses given in the
1390 trace. We can do better:
1391
1392 @example
1393 drepper$ mtrace tst errlog
1394 - 0x08064cc8 Free 2 was never alloc'd /home/drepper/tst.c:39
1395 - 0x08064ce0 Free 3 was never alloc'd /home/drepper/tst.c:39
1396 - 0x08064cf8 Free 4 was never alloc'd /home/drepper/tst.c:39
1397
1398 Memory not freed:
1399 -----------------
1400 Address Size Caller
1401 0x08064c48 0x14 at /home/drepper/tst.c:33
1402 0x08064c60 0x14 at /home/drepper/tst.c:33
1403 0x08064c78 0x14 at /home/drepper/tst.c:33
1404 0x08064c90 0x14 at /home/drepper/tst.c:33
1405 @end example
1406
1407 Suddenly the output makes much more sense and the user can see
1408 immediately where the function calls causing the trouble can be found.
1409
1410 Interpreting this output is not complicated. There are at most two
1411 different situations being detected. First, @code{free} was called for
1412 pointers which were never returned by one of the allocation functions.
1413 This is usually a very bad problem and what this looks like is shown in
1414 the first three lines of the output. Situations like this are quite
1415 rare and if they appear they show up very drastically: the program
1416 normally crashes.
1417
1418 The other situation which is much harder to detect are memory leaks. As
1419 you can see in the output the @code{mtrace} function collects all this
1420 information and so can say that the program calls an allocation function
1421 from line 33 in the source file @file{/home/drepper/tst-mtrace.c} four
1422 times without freeing this memory before the program terminates.
1423 Whether this is a real problem remains to be investigated.
1424
1425 @node Obstacks
1426 @subsection Obstacks
1427 @cindex obstacks
1428
1429 An @dfn{obstack} is a pool of memory containing a stack of objects. You
1430 can create any number of separate obstacks, and then allocate objects in
1431 specified obstacks. Within each obstack, the last object allocated must
1432 always be the first one freed, but distinct obstacks are independent of
1433 each other.
1434
1435 Aside from this one constraint of order of freeing, obstacks are totally
1436 general: an obstack can contain any number of objects of any size. They
1437 are implemented with macros, so allocation is usually very fast as long as
1438 the objects are usually small. And the only space overhead per object is
1439 the padding needed to start each object on a suitable boundary.
1440
1441 @menu
1442 * Creating Obstacks:: How to declare an obstack in your program.
1443 * Preparing for Obstacks:: Preparations needed before you can
1444 use obstacks.
1445 * Allocation in an Obstack:: Allocating objects in an obstack.
1446 * Freeing Obstack Objects:: Freeing objects in an obstack.
1447 * Obstack Functions:: The obstack functions are both
1448 functions and macros.
1449 * Growing Objects:: Making an object bigger by stages.
1450 * Extra Fast Growing:: Extra-high-efficiency (though more
1451 complicated) growing objects.
1452 * Status of an Obstack:: Inquiries about the status of an obstack.
1453 * Obstacks Data Alignment:: Controlling alignment of objects in obstacks.
1454 * Obstack Chunks:: How obstacks obtain and release chunks;
1455 efficiency considerations.
1456 * Summary of Obstacks::
1457 @end menu
1458
1459 @node Creating Obstacks
1460 @subsubsection Creating Obstacks
1461
1462 The utilities for manipulating obstacks are declared in the header
1463 file @file{obstack.h}.
1464 @pindex obstack.h
1465
1466 @comment obstack.h
1467 @comment GNU
1468 @deftp {Data Type} {struct obstack}
1469 An obstack is represented by a data structure of type @code{struct
1470 obstack}. This structure has a small fixed size; it records the status
1471 of the obstack and how to find the space in which objects are allocated.
1472 It does not contain any of the objects themselves. You should not try
1473 to access the contents of the structure directly; use only the functions
1474 described in this chapter.
1475 @end deftp
1476
1477 You can declare variables of type @code{struct obstack} and use them as
1478 obstacks, or you can allocate obstacks dynamically like any other kind
1479 of object. Dynamic allocation of obstacks allows your program to have a
1480 variable number of different stacks. (You can even allocate an
1481 obstack structure in another obstack, but this is rarely useful.)
1482
1483 All the functions that work with obstacks require you to specify which
1484 obstack to use. You do this with a pointer of type @code{struct obstack
1485 *}. In the following, we often say ``an obstack'' when strictly
1486 speaking the object at hand is such a pointer.
1487
1488 The objects in the obstack are packed into large blocks called
1489 @dfn{chunks}. The @code{struct obstack} structure points to a chain of
1490 the chunks currently in use.
1491
1492 The obstack library obtains a new chunk whenever you allocate an object
1493 that won't fit in the previous chunk. Since the obstack library manages
1494 chunks automatically, you don't need to pay much attention to them, but
1495 you do need to supply a function which the obstack library should use to
1496 get a chunk. Usually you supply a function which uses @code{malloc}
1497 directly or indirectly. You must also supply a function to free a chunk.
1498 These matters are described in the following section.
1499
1500 @node Preparing for Obstacks
1501 @subsubsection Preparing for Using Obstacks
1502
1503 Each source file in which you plan to use the obstack functions
1504 must include the header file @file{obstack.h}, like this:
1505
1506 @smallexample
1507 #include <obstack.h>
1508 @end smallexample
1509
1510 @findex obstack_chunk_alloc
1511 @findex obstack_chunk_free
1512 Also, if the source file uses the macro @code{obstack_init}, it must
1513 declare or define two functions or macros that will be called by the
1514 obstack library. One, @code{obstack_chunk_alloc}, is used to allocate
1515 the chunks of memory into which objects are packed. The other,
1516 @code{obstack_chunk_free}, is used to return chunks when the objects in
1517 them are freed. These macros should appear before any use of obstacks
1518 in the source file.
1519
1520 Usually these are defined to use @code{malloc} via the intermediary
1521 @code{xmalloc} (@pxref{Unconstrained Allocation}). This is done with
1522 the following pair of macro definitions:
1523
1524 @smallexample
1525 #define obstack_chunk_alloc xmalloc
1526 #define obstack_chunk_free free
1527 @end smallexample
1528
1529 @noindent
1530 Though the memory you get using obstacks really comes from @code{malloc},
1531 using obstacks is faster because @code{malloc} is called less often, for
1532 larger blocks of memory. @xref{Obstack Chunks}, for full details.
1533
1534 At run time, before the program can use a @code{struct obstack} object
1535 as an obstack, it must initialize the obstack by calling
1536 @code{obstack_init}.
1537
1538 @comment obstack.h
1539 @comment GNU
1540 @deftypefun int obstack_init (struct obstack *@var{obstack-ptr})
1541 Initialize obstack @var{obstack-ptr} for allocation of objects. This
1542 function calls the obstack's @code{obstack_chunk_alloc} function. If
1543 allocation of memory fails, the function pointed to by
1544 @code{obstack_alloc_failed_handler} is called. The @code{obstack_init}
1545 function always returns 1 (Compatibility notice: Former versions of
1546 obstack returned 0 if allocation failed).
1547 @end deftypefun
1548
1549 Here are two examples of how to allocate the space for an obstack and
1550 initialize it. First, an obstack that is a static variable:
1551
1552 @smallexample
1553 static struct obstack myobstack;
1554 @dots{}
1555 obstack_init (&myobstack);
1556 @end smallexample
1557
1558 @noindent
1559 Second, an obstack that is itself dynamically allocated:
1560
1561 @smallexample
1562 struct obstack *myobstack_ptr
1563 = (struct obstack *) xmalloc (sizeof (struct obstack));
1564
1565 obstack_init (myobstack_ptr);
1566 @end smallexample
1567
1568 @comment obstack.h
1569 @comment GNU
1570 @defvar obstack_alloc_failed_handler
1571 The value of this variable is a pointer to a function that
1572 @code{obstack} uses when @code{obstack_chunk_alloc} fails to allocate
1573 memory. The default action is to print a message and abort.
1574 You should supply a function that either calls @code{exit}
1575 (@pxref{Program Termination}) or @code{longjmp} (@pxref{Non-Local
1576 Exits}) and doesn't return.
1577
1578 @smallexample
1579 void my_obstack_alloc_failed (void)
1580 @dots{}
1581 obstack_alloc_failed_handler = &my_obstack_alloc_failed;
1582 @end smallexample
1583
1584 @end defvar
1585
1586 @node Allocation in an Obstack
1587 @subsubsection Allocation in an Obstack
1588 @cindex allocation (obstacks)
1589
1590 The most direct way to allocate an object in an obstack is with
1591 @code{obstack_alloc}, which is invoked almost like @code{malloc}.
1592
1593 @comment obstack.h
1594 @comment GNU
1595 @deftypefun {void *} obstack_alloc (struct obstack *@var{obstack-ptr}, int @var{size})
1596 This allocates an uninitialized block of @var{size} bytes in an obstack
1597 and returns its address. Here @var{obstack-ptr} specifies which obstack
1598 to allocate the block in; it is the address of the @code{struct obstack}
1599 object which represents the obstack. Each obstack function or macro
1600 requires you to specify an @var{obstack-ptr} as the first argument.
1601
1602 This function calls the obstack's @code{obstack_chunk_alloc} function if
1603 it needs to allocate a new chunk of memory; it calls
1604 @code{obstack_alloc_failed_handler} if allocation of memory by
1605 @code{obstack_chunk_alloc} failed.
1606 @end deftypefun
1607
1608 For example, here is a function that allocates a copy of a string @var{str}
1609 in a specific obstack, which is in the variable @code{string_obstack}:
1610
1611 @smallexample
1612 struct obstack string_obstack;
1613
1614 char *
1615 copystring (char *string)
1616 @{
1617 size_t len = strlen (string) + 1;
1618 char *s = (char *) obstack_alloc (&string_obstack, len);
1619 memcpy (s, string, len);
1620 return s;
1621 @}
1622 @end smallexample
1623
1624 To allocate a block with specified contents, use the function
1625 @code{obstack_copy}, declared like this:
1626
1627 @comment obstack.h
1628 @comment GNU
1629 @deftypefun {void *} obstack_copy (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
1630 This allocates a block and initializes it by copying @var{size}
1631 bytes of data starting at @var{address}. It calls
1632 @code{obstack_alloc_failed_handler} if allocation of memory by
1633 @code{obstack_chunk_alloc} failed.
1634 @end deftypefun
1635
1636 @comment obstack.h
1637 @comment GNU
1638 @deftypefun {void *} obstack_copy0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
1639 Like @code{obstack_copy}, but appends an extra byte containing a null
1640 character. This extra byte is not counted in the argument @var{size}.
1641 @end deftypefun
1642
1643 The @code{obstack_copy0} function is convenient for copying a sequence
1644 of characters into an obstack as a null-terminated string. Here is an
1645 example of its use:
1646
1647 @smallexample
1648 char *
1649 obstack_savestring (char *addr, int size)
1650 @{
1651 return obstack_copy0 (&myobstack, addr, size);
1652 @}
1653 @end smallexample
1654
1655 @noindent
1656 Contrast this with the previous example of @code{savestring} using
1657 @code{malloc} (@pxref{Basic Allocation}).
1658
1659 @node Freeing Obstack Objects
1660 @subsubsection Freeing Objects in an Obstack
1661 @cindex freeing (obstacks)
1662
1663 To free an object allocated in an obstack, use the function
1664 @code{obstack_free}. Since the obstack is a stack of objects, freeing
1665 one object automatically frees all other objects allocated more recently
1666 in the same obstack.
1667
1668 @comment obstack.h
1669 @comment GNU
1670 @deftypefun void obstack_free (struct obstack *@var{obstack-ptr}, void *@var{object})
1671 If @var{object} is a null pointer, everything allocated in the obstack
1672 is freed. Otherwise, @var{object} must be the address of an object
1673 allocated in the obstack. Then @var{object} is freed, along with
1674 everything allocated in @var{obstack} since @var{object}.
1675 @end deftypefun
1676
1677 Note that if @var{object} is a null pointer, the result is an
1678 uninitialized obstack. To free all memory in an obstack but leave it
1679 valid for further allocation, call @code{obstack_free} with the address
1680 of the first object allocated on the obstack:
1681
1682 @smallexample
1683 obstack_free (obstack_ptr, first_object_allocated_ptr);
1684 @end smallexample
1685
1686 Recall that the objects in an obstack are grouped into chunks. When all
1687 the objects in a chunk become free, the obstack library automatically
1688 frees the chunk (@pxref{Preparing for Obstacks}). Then other
1689 obstacks, or non-obstack allocation, can reuse the space of the chunk.
1690
1691 @node Obstack Functions
1692 @subsubsection Obstack Functions and Macros
1693 @cindex macros
1694
1695 The interfaces for using obstacks may be defined either as functions or
1696 as macros, depending on the compiler. The obstack facility works with
1697 all C compilers, including both @w{ISO C} and traditional C, but there are
1698 precautions you must take if you plan to use compilers other than GNU C.
1699
1700 If you are using an old-fashioned @w{non-ISO C} compiler, all the obstack
1701 ``functions'' are actually defined only as macros. You can call these
1702 macros like functions, but you cannot use them in any other way (for
1703 example, you cannot take their address).
1704
1705 Calling the macros requires a special precaution: namely, the first
1706 operand (the obstack pointer) may not contain any side effects, because
1707 it may be computed more than once. For example, if you write this:
1708
1709 @smallexample
1710 obstack_alloc (get_obstack (), 4);
1711 @end smallexample
1712
1713 @noindent
1714 you will find that @code{get_obstack} may be called several times.
1715 If you use @code{*obstack_list_ptr++} as the obstack pointer argument,
1716 you will get very strange results since the incrementation may occur
1717 several times.
1718
1719 In @w{ISO C}, each function has both a macro definition and a function
1720 definition. The function definition is used if you take the address of the
1721 function without calling it. An ordinary call uses the macro definition by
1722 default, but you can request the function definition instead by writing the
1723 function name in parentheses, as shown here:
1724
1725 @smallexample
1726 char *x;
1727 void *(*funcp) ();
1728 /* @r{Use the macro}. */
1729 x = (char *) obstack_alloc (obptr, size);
1730 /* @r{Call the function}. */
1731 x = (char *) (obstack_alloc) (obptr, size);
1732 /* @r{Take the address of the function}. */
1733 funcp = obstack_alloc;
1734 @end smallexample
1735
1736 @noindent
1737 This is the same situation that exists in @w{ISO C} for the standard library
1738 functions. @xref{Macro Definitions}.
1739
1740 @strong{Warning:} When you do use the macros, you must observe the
1741 precaution of avoiding side effects in the first operand, even in @w{ISO C}.
1742
1743 If you use the GNU C compiler, this precaution is not necessary, because
1744 various language extensions in GNU C permit defining the macros so as to
1745 compute each argument only once.
1746
1747 @node Growing Objects
1748 @subsubsection Growing Objects
1749 @cindex growing objects (in obstacks)
1750 @cindex changing the size of a block (obstacks)
1751
1752 Because memory in obstack chunks is used sequentially, it is possible to
1753 build up an object step by step, adding one or more bytes at a time to the
1754 end of the object. With this technique, you do not need to know how much
1755 data you will put in the object until you come to the end of it. We call
1756 this the technique of @dfn{growing objects}. The special functions
1757 for adding data to the growing object are described in this section.
1758
1759 You don't need to do anything special when you start to grow an object.
1760 Using one of the functions to add data to the object automatically
1761 starts it. However, it is necessary to say explicitly when the object is
1762 finished. This is done with the function @code{obstack_finish}.
1763
1764 The actual address of the object thus built up is not known until the
1765 object is finished. Until then, it always remains possible that you will
1766 add so much data that the object must be copied into a new chunk.
1767
1768 While the obstack is in use for a growing object, you cannot use it for
1769 ordinary allocation of another object. If you try to do so, the space
1770 already added to the growing object will become part of the other object.
1771
1772 @comment obstack.h
1773 @comment GNU
1774 @deftypefun void obstack_blank (struct obstack *@var{obstack-ptr}, int @var{size})
1775 The most basic function for adding to a growing object is
1776 @code{obstack_blank}, which adds space without initializing it.
1777 @end deftypefun
1778
1779 @comment obstack.h
1780 @comment GNU
1781 @deftypefun void obstack_grow (struct obstack *@var{obstack-ptr}, void *@var{data}, int @var{size})
1782 To add a block of initialized space, use @code{obstack_grow}, which is
1783 the growing-object analogue of @code{obstack_copy}. It adds @var{size}
1784 bytes of data to the growing object, copying the contents from
1785 @var{data}.
1786 @end deftypefun
1787
1788 @comment obstack.h
1789 @comment GNU
1790 @deftypefun void obstack_grow0 (struct obstack *@var{obstack-ptr}, void *@var{data}, int @var{size})
1791 This is the growing-object analogue of @code{obstack_copy0}. It adds
1792 @var{size} bytes copied from @var{data}, followed by an additional null
1793 character.
1794 @end deftypefun
1795
1796 @comment obstack.h
1797 @comment GNU
1798 @deftypefun void obstack_1grow (struct obstack *@var{obstack-ptr}, char @var{c})
1799 To add one character at a time, use the function @code{obstack_1grow}.
1800 It adds a single byte containing @var{c} to the growing object.
1801 @end deftypefun
1802
1803 @comment obstack.h
1804 @comment GNU
1805 @deftypefun void obstack_ptr_grow (struct obstack *@var{obstack-ptr}, void *@var{data})
1806 Adding the value of a pointer one can use the function
1807 @code{obstack_ptr_grow}. It adds @code{sizeof (void *)} bytes
1808 containing the value of @var{data}.
1809 @end deftypefun
1810
1811 @comment obstack.h
1812 @comment GNU
1813 @deftypefun void obstack_int_grow (struct obstack *@var{obstack-ptr}, int @var{data})
1814 A single value of type @code{int} can be added by using the
1815 @code{obstack_int_grow} function. It adds @code{sizeof (int)} bytes to
1816 the growing object and initializes them with the value of @var{data}.
1817 @end deftypefun
1818
1819 @comment obstack.h
1820 @comment GNU
1821 @deftypefun {void *} obstack_finish (struct obstack *@var{obstack-ptr})
1822 When you are finished growing the object, use the function
1823 @code{obstack_finish} to close it off and return its final address.
1824
1825 Once you have finished the object, the obstack is available for ordinary
1826 allocation or for growing another object.
1827
1828 This function can return a null pointer under the same conditions as
1829 @code{obstack_alloc} (@pxref{Allocation in an Obstack}).
1830 @end deftypefun
1831
1832 When you build an object by growing it, you will probably need to know
1833 afterward how long it became. You need not keep track of this as you grow
1834 the object, because you can find out the length from the obstack just
1835 before finishing the object with the function @code{obstack_object_size},
1836 declared as follows:
1837
1838 @comment obstack.h
1839 @comment GNU
1840 @deftypefun int obstack_object_size (struct obstack *@var{obstack-ptr})
1841 This function returns the current size of the growing object, in bytes.
1842 Remember to call this function @emph{before} finishing the object.
1843 After it is finished, @code{obstack_object_size} will return zero.
1844 @end deftypefun
1845
1846 If you have started growing an object and wish to cancel it, you should
1847 finish it and then free it, like this:
1848
1849 @smallexample
1850 obstack_free (obstack_ptr, obstack_finish (obstack_ptr));
1851 @end smallexample
1852
1853 @noindent
1854 This has no effect if no object was growing.
1855
1856 @cindex shrinking objects
1857 You can use @code{obstack_blank} with a negative size argument to make
1858 the current object smaller. Just don't try to shrink it beyond zero
1859 length---there's no telling what will happen if you do that.
1860
1861 @node Extra Fast Growing
1862 @subsubsection Extra Fast Growing Objects
1863 @cindex efficiency and obstacks
1864
1865 The usual functions for growing objects incur overhead for checking
1866 whether there is room for the new growth in the current chunk. If you
1867 are frequently constructing objects in small steps of growth, this
1868 overhead can be significant.
1869
1870 You can reduce the overhead by using special ``fast growth''
1871 functions that grow the object without checking. In order to have a
1872 robust program, you must do the checking yourself. If you do this checking
1873 in the simplest way each time you are about to add data to the object, you
1874 have not saved anything, because that is what the ordinary growth
1875 functions do. But if you can arrange to check less often, or check
1876 more efficiently, then you make the program faster.
1877
1878 The function @code{obstack_room} returns the amount of room available
1879 in the current chunk. It is declared as follows:
1880
1881 @comment obstack.h
1882 @comment GNU
1883 @deftypefun int obstack_room (struct obstack *@var{obstack-ptr})
1884 This returns the number of bytes that can be added safely to the current
1885 growing object (or to an object about to be started) in obstack
1886 @var{obstack} using the fast growth functions.
1887 @end deftypefun
1888
1889 While you know there is room, you can use these fast growth functions
1890 for adding data to a growing object:
1891
1892 @comment obstack.h
1893 @comment GNU
1894 @deftypefun void obstack_1grow_fast (struct obstack *@var{obstack-ptr}, char @var{c})
1895 The function @code{obstack_1grow_fast} adds one byte containing the
1896 character @var{c} to the growing object in obstack @var{obstack-ptr}.
1897 @end deftypefun
1898
1899 @comment obstack.h
1900 @comment GNU
1901 @deftypefun void obstack_ptr_grow_fast (struct obstack *@var{obstack-ptr}, void *@var{data})
1902 The function @code{obstack_ptr_grow_fast} adds @code{sizeof (void *)}
1903 bytes containing the value of @var{data} to the growing object in
1904 obstack @var{obstack-ptr}.
1905 @end deftypefun
1906
1907 @comment obstack.h
1908 @comment GNU
1909 @deftypefun void obstack_int_grow_fast (struct obstack *@var{obstack-ptr}, int @var{data})
1910 The function @code{obstack_int_grow_fast} adds @code{sizeof (int)} bytes
1911 containing the value of @var{data} to the growing object in obstack
1912 @var{obstack-ptr}.
1913 @end deftypefun
1914
1915 @comment obstack.h
1916 @comment GNU
1917 @deftypefun void obstack_blank_fast (struct obstack *@var{obstack-ptr}, int @var{size})
1918 The function @code{obstack_blank_fast} adds @var{size} bytes to the
1919 growing object in obstack @var{obstack-ptr} without initializing them.
1920 @end deftypefun
1921
1922 When you check for space using @code{obstack_room} and there is not
1923 enough room for what you want to add, the fast growth functions
1924 are not safe. In this case, simply use the corresponding ordinary
1925 growth function instead. Very soon this will copy the object to a
1926 new chunk; then there will be lots of room available again.
1927
1928 So, each time you use an ordinary growth function, check afterward for
1929 sufficient space using @code{obstack_room}. Once the object is copied
1930 to a new chunk, there will be plenty of space again, so the program will
1931 start using the fast growth functions again.
1932
1933 Here is an example:
1934
1935 @smallexample
1936 @group
1937 void
1938 add_string (struct obstack *obstack, const char *ptr, int len)
1939 @{
1940 while (len > 0)
1941 @{
1942 int room = obstack_room (obstack);
1943 if (room == 0)
1944 @{
1945 /* @r{Not enough room. Add one character slowly,}
1946 @r{which may copy to a new chunk and make room.} */
1947 obstack_1grow (obstack, *ptr++);
1948 len--;
1949 @}
1950 else
1951 @{
1952 if (room > len)
1953 room = len;
1954 /* @r{Add fast as much as we have room for.} */
1955 len -= room;
1956 while (room-- > 0)
1957 obstack_1grow_fast (obstack, *ptr++);
1958 @}
1959 @}
1960 @}
1961 @end group
1962 @end smallexample
1963
1964 @node Status of an Obstack
1965 @subsubsection Status of an Obstack
1966 @cindex obstack status
1967 @cindex status of obstack
1968
1969 Here are functions that provide information on the current status of
1970 allocation in an obstack. You can use them to learn about an object while
1971 still growing it.
1972
1973 @comment obstack.h
1974 @comment GNU
1975 @deftypefun {void *} obstack_base (struct obstack *@var{obstack-ptr})
1976 This function returns the tentative address of the beginning of the
1977 currently growing object in @var{obstack-ptr}. If you finish the object
1978 immediately, it will have that address. If you make it larger first, it
1979 may outgrow the current chunk---then its address will change!
1980
1981 If no object is growing, this value says where the next object you
1982 allocate will start (once again assuming it fits in the current
1983 chunk).
1984 @end deftypefun
1985
1986 @comment obstack.h
1987 @comment GNU
1988 @deftypefun {void *} obstack_next_free (struct obstack *@var{obstack-ptr})
1989 This function returns the address of the first free byte in the current
1990 chunk of obstack @var{obstack-ptr}. This is the end of the currently
1991 growing object. If no object is growing, @code{obstack_next_free}
1992 returns the same value as @code{obstack_base}.
1993 @end deftypefun
1994
1995 @comment obstack.h
1996 @comment GNU
1997 @deftypefun int obstack_object_size (struct obstack *@var{obstack-ptr})
1998 This function returns the size in bytes of the currently growing object.
1999 This is equivalent to
2000
2001 @smallexample
2002 obstack_next_free (@var{obstack-ptr}) - obstack_base (@var{obstack-ptr})
2003 @end smallexample
2004 @end deftypefun
2005
2006 @node Obstacks Data Alignment
2007 @subsubsection Alignment of Data in Obstacks
2008 @cindex alignment (in obstacks)
2009
2010 Each obstack has an @dfn{alignment boundary}; each object allocated in
2011 the obstack automatically starts on an address that is a multiple of the
2012 specified boundary. By default, this boundary is aligned so that
2013 the object can hold any type of data.
2014
2015 To access an obstack's alignment boundary, use the macro
2016 @code{obstack_alignment_mask}, whose function prototype looks like
2017 this:
2018
2019 @comment obstack.h
2020 @comment GNU
2021 @deftypefn Macro int obstack_alignment_mask (struct obstack *@var{obstack-ptr})
2022 The value is a bit mask; a bit that is 1 indicates that the corresponding
2023 bit in the address of an object should be 0. The mask value should be one
2024 less than a power of 2; the effect is that all object addresses are
2025 multiples of that power of 2. The default value of the mask is a value
2026 that allows aligned objects to hold any type of data: for example, if
2027 its value is 3, any type of data can be stored at locations whose
2028 addresses are multiples of 4. A mask value of 0 means an object can start
2029 on any multiple of 1 (that is, no alignment is required).
2030
2031 The expansion of the macro @code{obstack_alignment_mask} is an lvalue,
2032 so you can alter the mask by assignment. For example, this statement:
2033
2034 @smallexample
2035 obstack_alignment_mask (obstack_ptr) = 0;
2036 @end smallexample
2037
2038 @noindent
2039 has the effect of turning off alignment processing in the specified obstack.
2040 @end deftypefn
2041
2042 Note that a change in alignment mask does not take effect until
2043 @emph{after} the next time an object is allocated or finished in the
2044 obstack. If you are not growing an object, you can make the new
2045 alignment mask take effect immediately by calling @code{obstack_finish}.
2046 This will finish a zero-length object and then do proper alignment for
2047 the next object.
2048
2049 @node Obstack Chunks
2050 @subsubsection Obstack Chunks
2051 @cindex efficiency of chunks
2052 @cindex chunks
2053
2054 Obstacks work by allocating space for themselves in large chunks, and
2055 then parceling out space in the chunks to satisfy your requests. Chunks
2056 are normally 4096 bytes long unless you specify a different chunk size.
2057 The chunk size includes 8 bytes of overhead that are not actually used
2058 for storing objects. Regardless of the specified size, longer chunks
2059 will be allocated when necessary for long objects.
2060
2061 The obstack library allocates chunks by calling the function
2062 @code{obstack_chunk_alloc}, which you must define. When a chunk is no
2063 longer needed because you have freed all the objects in it, the obstack
2064 library frees the chunk by calling @code{obstack_chunk_free}, which you
2065 must also define.
2066
2067 These two must be defined (as macros) or declared (as functions) in each
2068 source file that uses @code{obstack_init} (@pxref{Creating Obstacks}).
2069 Most often they are defined as macros like this:
2070
2071 @smallexample
2072 #define obstack_chunk_alloc malloc
2073 #define obstack_chunk_free free
2074 @end smallexample
2075
2076 Note that these are simple macros (no arguments). Macro definitions with
2077 arguments will not work! It is necessary that @code{obstack_chunk_alloc}
2078 or @code{obstack_chunk_free}, alone, expand into a function name if it is
2079 not itself a function name.
2080
2081 If you allocate chunks with @code{malloc}, the chunk size should be a
2082 power of 2. The default chunk size, 4096, was chosen because it is long
2083 enough to satisfy many typical requests on the obstack yet short enough
2084 not to waste too much memory in the portion of the last chunk not yet used.
2085
2086 @comment obstack.h
2087 @comment GNU
2088 @deftypefn Macro int obstack_chunk_size (struct obstack *@var{obstack-ptr})
2089 This returns the chunk size of the given obstack.
2090 @end deftypefn
2091
2092 Since this macro expands to an lvalue, you can specify a new chunk size by
2093 assigning it a new value. Doing so does not affect the chunks already
2094 allocated, but will change the size of chunks allocated for that particular
2095 obstack in the future. It is unlikely to be useful to make the chunk size
2096 smaller, but making it larger might improve efficiency if you are
2097 allocating many objects whose size is comparable to the chunk size. Here
2098 is how to do so cleanly:
2099
2100 @smallexample
2101 if (obstack_chunk_size (obstack_ptr) < @var{new-chunk-size})
2102 obstack_chunk_size (obstack_ptr) = @var{new-chunk-size};
2103 @end smallexample
2104
2105 @node Summary of Obstacks
2106 @subsubsection Summary of Obstack Functions
2107
2108 Here is a summary of all the functions associated with obstacks. Each
2109 takes the address of an obstack (@code{struct obstack *}) as its first
2110 argument.
2111
2112 @table @code
2113 @item void obstack_init (struct obstack *@var{obstack-ptr})
2114 Initialize use of an obstack. @xref{Creating Obstacks}.
2115
2116 @item void *obstack_alloc (struct obstack *@var{obstack-ptr}, int @var{size})
2117 Allocate an object of @var{size} uninitialized bytes.
2118 @xref{Allocation in an Obstack}.
2119
2120 @item void *obstack_copy (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2121 Allocate an object of @var{size} bytes, with contents copied from
2122 @var{address}. @xref{Allocation in an Obstack}.
2123
2124 @item void *obstack_copy0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2125 Allocate an object of @var{size}+1 bytes, with @var{size} of them copied
2126 from @var{address}, followed by a null character at the end.
2127 @xref{Allocation in an Obstack}.
2128
2129 @item void obstack_free (struct obstack *@var{obstack-ptr}, void *@var{object})
2130 Free @var{object} (and everything allocated in the specified obstack
2131 more recently than @var{object}). @xref{Freeing Obstack Objects}.
2132
2133 @item void obstack_blank (struct obstack *@var{obstack-ptr}, int @var{size})
2134 Add @var{size} uninitialized bytes to a growing object.
2135 @xref{Growing Objects}.
2136
2137 @item void obstack_grow (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2138 Add @var{size} bytes, copied from @var{address}, to a growing object.
2139 @xref{Growing Objects}.
2140
2141 @item void obstack_grow0 (struct obstack *@var{obstack-ptr}, void *@var{address}, int @var{size})
2142 Add @var{size} bytes, copied from @var{address}, to a growing object,
2143 and then add another byte containing a null character. @xref{Growing
2144 Objects}.
2145
2146 @item void obstack_1grow (struct obstack *@var{obstack-ptr}, char @var{data-char})
2147 Add one byte containing @var{data-char} to a growing object.
2148 @xref{Growing Objects}.
2149
2150 @item void *obstack_finish (struct obstack *@var{obstack-ptr})
2151 Finalize the object that is growing and return its permanent address.
2152 @xref{Growing Objects}.
2153
2154 @item int obstack_object_size (struct obstack *@var{obstack-ptr})
2155 Get the current size of the currently growing object. @xref{Growing
2156 Objects}.
2157
2158 @item void obstack_blank_fast (struct obstack *@var{obstack-ptr}, int @var{size})
2159 Add @var{size} uninitialized bytes to a growing object without checking
2160 that there is enough room. @xref{Extra Fast Growing}.
2161
2162 @item void obstack_1grow_fast (struct obstack *@var{obstack-ptr}, char @var{data-char})
2163 Add one byte containing @var{data-char} to a growing object without
2164 checking that there is enough room. @xref{Extra Fast Growing}.
2165
2166 @item int obstack_room (struct obstack *@var{obstack-ptr})
2167 Get the amount of room now available for growing the current object.
2168 @xref{Extra Fast Growing}.
2169
2170 @item int obstack_alignment_mask (struct obstack *@var{obstack-ptr})
2171 The mask used for aligning the beginning of an object. This is an
2172 lvalue. @xref{Obstacks Data Alignment}.
2173
2174 @item int obstack_chunk_size (struct obstack *@var{obstack-ptr})
2175 The size for allocating chunks. This is an lvalue. @xref{Obstack Chunks}.
2176
2177 @item void *obstack_base (struct obstack *@var{obstack-ptr})
2178 Tentative starting address of the currently growing object.
2179 @xref{Status of an Obstack}.
2180
2181 @item void *obstack_next_free (struct obstack *@var{obstack-ptr})
2182 Address just after the end of the currently growing object.
2183 @xref{Status of an Obstack}.
2184 @end table
2185
2186 @node Variable Size Automatic
2187 @subsection Automatic Storage with Variable Size
2188 @cindex automatic freeing
2189 @cindex @code{alloca} function
2190 @cindex automatic storage with variable size
2191
2192 The function @code{alloca} supports a kind of half-dynamic allocation in
2193 which blocks are allocated dynamically but freed automatically.
2194
2195 Allocating a block with @code{alloca} is an explicit action; you can
2196 allocate as many blocks as you wish, and compute the size at run time. But
2197 all the blocks are freed when you exit the function that @code{alloca} was
2198 called from, just as if they were automatic variables declared in that
2199 function. There is no way to free the space explicitly.
2200
2201 The prototype for @code{alloca} is in @file{stdlib.h}. This function is
2202 a BSD extension.
2203 @pindex stdlib.h
2204
2205 @comment stdlib.h
2206 @comment GNU, BSD
2207 @deftypefun {void *} alloca (size_t @var{size})
2208 The return value of @code{alloca} is the address of a block of @var{size}
2209 bytes of memory, allocated in the stack frame of the calling function.
2210 @end deftypefun
2211
2212 Do not use @code{alloca} inside the arguments of a function call---you
2213 will get unpredictable results, because the stack space for the
2214 @code{alloca} would appear on the stack in the middle of the space for
2215 the function arguments. An example of what to avoid is @code{foo (x,
2216 alloca (4), y)}.
2217 @c This might get fixed in future versions of GCC, but that won't make
2218 @c it safe with compilers generally.
2219
2220 @menu
2221 * Alloca Example:: Example of using @code{alloca}.
2222 * Advantages of Alloca:: Reasons to use @code{alloca}.
2223 * Disadvantages of Alloca:: Reasons to avoid @code{alloca}.
2224 * GNU C Variable-Size Arrays:: Only in GNU C, here is an alternative
2225 method of allocating dynamically and
2226 freeing automatically.
2227 @end menu
2228
2229 @node Alloca Example
2230 @subsubsection @code{alloca} Example
2231
2232 As an example of the use of @code{alloca}, here is a function that opens
2233 a file name made from concatenating two argument strings, and returns a
2234 file descriptor or minus one signifying failure:
2235
2236 @smallexample
2237 int
2238 open2 (char *str1, char *str2, int flags, int mode)
2239 @{
2240 char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
2241 stpcpy (stpcpy (name, str1), str2);
2242 return open (name, flags, mode);
2243 @}
2244 @end smallexample
2245
2246 @noindent
2247 Here is how you would get the same results with @code{malloc} and
2248 @code{free}:
2249
2250 @smallexample
2251 int
2252 open2 (char *str1, char *str2, int flags, int mode)
2253 @{
2254 char *name = (char *) malloc (strlen (str1) + strlen (str2) + 1);
2255 int desc;
2256 if (name == 0)
2257 fatal ("virtual memory exceeded");
2258 stpcpy (stpcpy (name, str1), str2);
2259 desc = open (name, flags, mode);
2260 free (name);
2261 return desc;
2262 @}
2263 @end smallexample
2264
2265 As you can see, it is simpler with @code{alloca}. But @code{alloca} has
2266 other, more important advantages, and some disadvantages.
2267
2268 @node Advantages of Alloca
2269 @subsubsection Advantages of @code{alloca}
2270
2271 Here are the reasons why @code{alloca} may be preferable to @code{malloc}:
2272
2273 @itemize @bullet
2274 @item
2275 Using @code{alloca} wastes very little space and is very fast. (It is
2276 open-coded by the GNU C compiler.)
2277
2278 @item
2279 Since @code{alloca} does not have separate pools for different sizes of
2280 block, space used for any size block can be reused for any other size.
2281 @code{alloca} does not cause memory fragmentation.
2282
2283 @item
2284 @cindex longjmp
2285 Nonlocal exits done with @code{longjmp} (@pxref{Non-Local Exits})
2286 automatically free the space allocated with @code{alloca} when they exit
2287 through the function that called @code{alloca}. This is the most
2288 important reason to use @code{alloca}.
2289
2290 To illustrate this, suppose you have a function
2291 @code{open_or_report_error} which returns a descriptor, like
2292 @code{open}, if it succeeds, but does not return to its caller if it
2293 fails. If the file cannot be opened, it prints an error message and
2294 jumps out to the command level of your program using @code{longjmp}.
2295 Let's change @code{open2} (@pxref{Alloca Example}) to use this
2296 subroutine:@refill
2297
2298 @smallexample
2299 int
2300 open2 (char *str1, char *str2, int flags, int mode)
2301 @{
2302 char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
2303 stpcpy (stpcpy (name, str1), str2);
2304 return open_or_report_error (name, flags, mode);
2305 @}
2306 @end smallexample
2307
2308 @noindent
2309 Because of the way @code{alloca} works, the memory it allocates is
2310 freed even when an error occurs, with no special effort required.
2311
2312 By contrast, the previous definition of @code{open2} (which uses
2313 @code{malloc} and @code{free}) would develop a memory leak if it were
2314 changed in this way. Even if you are willing to make more changes to
2315 fix it, there is no easy way to do so.
2316 @end itemize
2317
2318 @node Disadvantages of Alloca
2319 @subsubsection Disadvantages of @code{alloca}
2320
2321 @cindex @code{alloca} disadvantages
2322 @cindex disadvantages of @code{alloca}
2323 These are the disadvantages of @code{alloca} in comparison with
2324 @code{malloc}:
2325
2326 @itemize @bullet
2327 @item
2328 If you try to allocate more memory than the machine can provide, you
2329 don't get a clean error message. Instead you get a fatal signal like
2330 the one you would get from an infinite recursion; probably a
2331 segmentation violation (@pxref{Program Error Signals}).
2332
2333 @item
2334 Some @nongnusystems{} fail to support @code{alloca}, so it is less
2335 portable. However, a slower emulation of @code{alloca} written in C
2336 is available for use on systems with this deficiency.
2337 @end itemize
2338
2339 @node GNU C Variable-Size Arrays
2340 @subsubsection GNU C Variable-Size Arrays
2341 @cindex variable-sized arrays
2342
2343 In GNU C, you can replace most uses of @code{alloca} with an array of
2344 variable size. Here is how @code{open2} would look then:
2345
2346 @smallexample
2347 int open2 (char *str1, char *str2, int flags, int mode)
2348 @{
2349 char name[strlen (str1) + strlen (str2) + 1];
2350 stpcpy (stpcpy (name, str1), str2);
2351 return open (name, flags, mode);
2352 @}
2353 @end smallexample
2354
2355 But @code{alloca} is not always equivalent to a variable-sized array, for
2356 several reasons:
2357
2358 @itemize @bullet
2359 @item
2360 A variable size array's space is freed at the end of the scope of the
2361 name of the array. The space allocated with @code{alloca}
2362 remains until the end of the function.
2363
2364 @item
2365 It is possible to use @code{alloca} within a loop, allocating an
2366 additional block on each iteration. This is impossible with
2367 variable-sized arrays.
2368 @end itemize
2369
2370 @strong{NB:} If you mix use of @code{alloca} and variable-sized arrays
2371 within one function, exiting a scope in which a variable-sized array was
2372 declared frees all blocks allocated with @code{alloca} during the
2373 execution of that scope.
2374
2375
2376 @node Resizing the Data Segment
2377 @section Resizing the Data Segment
2378
2379 The symbols in this section are declared in @file{unistd.h}.
2380
2381 You will not normally use the functions in this section, because the
2382 functions described in @ref{Memory Allocation} are easier to use. Those
2383 are interfaces to a @glibcadj{} memory allocator that uses the
2384 functions below itself. The functions below are simple interfaces to
2385 system calls.
2386
2387 @comment unistd.h
2388 @comment BSD
2389 @deftypefun int brk (void *@var{addr})
2390
2391 @code{brk} sets the high end of the calling process' data segment to
2392 @var{addr}.
2393
2394 The address of the end of a segment is defined to be the address of the
2395 last byte in the segment plus 1.
2396
2397 The function has no effect if @var{addr} is lower than the low end of
2398 the data segment. (This is considered success, by the way).
2399
2400 The function fails if it would cause the data segment to overlap another
2401 segment or exceed the process' data storage limit (@pxref{Limits on
2402 Resources}).
2403
2404 The function is named for a common historical case where data storage
2405 and the stack are in the same segment. Data storage allocation grows
2406 upward from the bottom of the segment while the stack grows downward
2407 toward it from the top of the segment and the curtain between them is
2408 called the @dfn{break}.
2409
2410 The return value is zero on success. On failure, the return value is
2411 @code{-1} and @code{errno} is set accordingly. The following @code{errno}
2412 values are specific to this function:
2413
2414 @table @code
2415 @item ENOMEM
2416 The request would cause the data segment to overlap another segment or
2417 exceed the process' data storage limit.
2418 @end table
2419
2420 @c The Brk system call in Linux (as opposed to the GNU C Library function)
2421 @c is considerably different. It always returns the new end of the data
2422 @c segment, whether it succeeds or fails. The GNU C library Brk determines
2423 @c it's a failure if and only if the system call returns an address less
2424 @c than the address requested.
2425
2426 @end deftypefun
2427
2428
2429 @comment unistd.h
2430 @comment BSD
2431 @deftypefun void *sbrk (ptrdiff_t @var{delta})
2432 This function is the same as @code{brk} except that you specify the new
2433 end of the data segment as an offset @var{delta} from the current end
2434 and on success the return value is the address of the resulting end of
2435 the data segment instead of zero.
2436
2437 This means you can use @samp{sbrk(0)} to find out what the current end
2438 of the data segment is.
2439
2440 @end deftypefun
2441
2442
2443
2444 @node Locking Pages
2445 @section Locking Pages
2446 @cindex locking pages
2447 @cindex memory lock
2448 @cindex paging
2449
2450 You can tell the system to associate a particular virtual memory page
2451 with a real page frame and keep it that way --- i.e., cause the page to
2452 be paged in if it isn't already and mark it so it will never be paged
2453 out and consequently will never cause a page fault. This is called
2454 @dfn{locking} a page.
2455
2456 The functions in this chapter lock and unlock the calling process'
2457 pages.
2458
2459 @menu
2460 * Why Lock Pages:: Reasons to read this section.
2461 * Locked Memory Details:: Everything you need to know locked
2462 memory
2463 * Page Lock Functions:: Here's how to do it.
2464 @end menu
2465
2466 @node Why Lock Pages
2467 @subsection Why Lock Pages
2468
2469 Because page faults cause paged out pages to be paged in transparently,
2470 a process rarely needs to be concerned about locking pages. However,
2471 there are two reasons people sometimes are:
2472
2473 @itemize @bullet
2474
2475 @item
2476 Speed. A page fault is transparent only insofar as the process is not
2477 sensitive to how long it takes to do a simple memory access. Time-critical
2478 processes, especially realtime processes, may not be able to wait or
2479 may not be able to tolerate variance in execution speed.
2480 @cindex realtime processing
2481 @cindex speed of execution
2482
2483 A process that needs to lock pages for this reason probably also needs
2484 priority among other processes for use of the CPU. @xref{Priority}.
2485
2486 In some cases, the programmer knows better than the system's demand
2487 paging allocator which pages should remain in real memory to optimize
2488 system performance. In this case, locking pages can help.
2489
2490 @item
2491 Privacy. If you keep secrets in virtual memory and that virtual memory
2492 gets paged out, that increases the chance that the secrets will get out.
2493 If a password gets written out to disk swap space, for example, it might
2494 still be there long after virtual and real memory have been wiped clean.
2495
2496 @end itemize
2497
2498 Be aware that when you lock a page, that's one fewer page frame that can
2499 be used to back other virtual memory (by the same or other processes),
2500 which can mean more page faults, which means the system runs more
2501 slowly. In fact, if you lock enough memory, some programs may not be
2502 able to run at all for lack of real memory.
2503
2504 @node Locked Memory Details
2505 @subsection Locked Memory Details
2506
2507 A memory lock is associated with a virtual page, not a real frame. The
2508 paging rule is: If a frame backs at least one locked page, don't page it
2509 out.
2510
2511 Memory locks do not stack. I.e., you can't lock a particular page twice
2512 so that it has to be unlocked twice before it is truly unlocked. It is
2513 either locked or it isn't.
2514
2515 A memory lock persists until the process that owns the memory explicitly
2516 unlocks it. (But process termination and exec cause the virtual memory
2517 to cease to exist, which you might say means it isn't locked any more).
2518
2519 Memory locks are not inherited by child processes. (But note that on a
2520 modern Unix system, immediately after a fork, the parent's and the
2521 child's virtual address space are backed by the same real page frames,
2522 so the child enjoys the parent's locks). @xref{Creating a Process}.
2523
2524 Because of its ability to impact other processes, only the superuser can
2525 lock a page. Any process can unlock its own page.
2526
2527 The system sets limits on the amount of memory a process can have locked
2528 and the amount of real memory it can have dedicated to it. @xref{Limits
2529 on Resources}.
2530
2531 In Linux, locked pages aren't as locked as you might think.
2532 Two virtual pages that are not shared memory can nonetheless be backed
2533 by the same real frame. The kernel does this in the name of efficiency
2534 when it knows both virtual pages contain identical data, and does it
2535 even if one or both of the virtual pages are locked.
2536
2537 But when a process modifies one of those pages, the kernel must get it a
2538 separate frame and fill it with the page's data. This is known as a
2539 @dfn{copy-on-write page fault}. It takes a small amount of time and in
2540 a pathological case, getting that frame may require I/O.
2541 @cindex copy-on-write page fault
2542 @cindex page fault, copy-on-write
2543
2544 To make sure this doesn't happen to your program, don't just lock the
2545 pages. Write to them as well, unless you know you won't write to them
2546 ever. And to make sure you have pre-allocated frames for your stack,
2547 enter a scope that declares a C automatic variable larger than the
2548 maximum stack size you will need, set it to something, then return from
2549 its scope.
2550
2551 @node Page Lock Functions
2552 @subsection Functions To Lock And Unlock Pages
2553
2554 The symbols in this section are declared in @file{sys/mman.h}. These
2555 functions are defined by POSIX.1b, but their availability depends on
2556 your kernel. If your kernel doesn't allow these functions, they exist
2557 but always fail. They @emph{are} available with a Linux kernel.
2558
2559 @strong{Portability Note:} POSIX.1b requires that when the @code{mlock}
2560 and @code{munlock} functions are available, the file @file{unistd.h}
2561 define the macro @code{_POSIX_MEMLOCK_RANGE} and the file
2562 @code{limits.h} define the macro @code{PAGESIZE} to be the size of a
2563 memory page in bytes. It requires that when the @code{mlockall} and
2564 @code{munlockall} functions are available, the @file{unistd.h} file
2565 define the macro @code{_POSIX_MEMLOCK}. @Theglibc{} conforms to
2566 this requirement.
2567
2568 @comment sys/mman.h
2569 @comment POSIX.1b
2570 @deftypefun int mlock (const void *@var{addr}, size_t @var{len})
2571
2572 @code{mlock} locks a range of the calling process' virtual pages.
2573
2574 The range of memory starts at address @var{addr} and is @var{len} bytes
2575 long. Actually, since you must lock whole pages, it is the range of
2576 pages that include any part of the specified range.
2577
2578 When the function returns successfully, each of those pages is backed by
2579 (connected to) a real frame (is resident) and is marked to stay that
2580 way. This means the function may cause page-ins and have to wait for
2581 them.
2582
2583 When the function fails, it does not affect the lock status of any
2584 pages.
2585
2586 The return value is zero if the function succeeds. Otherwise, it is
2587 @code{-1} and @code{errno} is set accordingly. @code{errno} values
2588 specific to this function are:
2589
2590 @table @code
2591 @item ENOMEM
2592 @itemize @bullet
2593 @item
2594 At least some of the specified address range does not exist in the
2595 calling process' virtual address space.
2596 @item
2597 The locking would cause the process to exceed its locked page limit.
2598 @end itemize
2599
2600 @item EPERM
2601 The calling process is not superuser.
2602
2603 @item EINVAL
2604 @var{len} is not positive.
2605
2606 @item ENOSYS
2607 The kernel does not provide @code{mlock} capability.
2608
2609 @end table
2610
2611 You can lock @emph{all} a process' memory with @code{mlockall}. You
2612 unlock memory with @code{munlock} or @code{munlockall}.
2613
2614 To avoid all page faults in a C program, you have to use
2615 @code{mlockall}, because some of the memory a program uses is hidden
2616 from the C code, e.g. the stack and automatic variables, and you
2617 wouldn't know what address to tell @code{mlock}.
2618
2619 @end deftypefun
2620
2621 @comment sys/mman.h
2622 @comment POSIX.1b
2623 @deftypefun int munlock (const void *@var{addr}, size_t @var{len})
2624
2625 @code{munlock} unlocks a range of the calling process' virtual pages.
2626
2627 @code{munlock} is the inverse of @code{mlock} and functions completely
2628 analogously to @code{mlock}, except that there is no @code{EPERM}
2629 failure.
2630
2631 @end deftypefun
2632
2633 @comment sys/mman.h
2634 @comment POSIX.1b
2635 @deftypefun int mlockall (int @var{flags})
2636
2637 @code{mlockall} locks all the pages in a process' virtual memory address
2638 space, and/or any that are added to it in the future. This includes the
2639 pages of the code, data and stack segment, as well as shared libraries,
2640 user space kernel data, shared memory, and memory mapped files.
2641
2642 @var{flags} is a string of single bit flags represented by the following
2643 macros. They tell @code{mlockall} which of its functions you want. All
2644 other bits must be zero.
2645
2646 @table @code
2647
2648 @item MCL_CURRENT
2649 Lock all pages which currently exist in the calling process' virtual
2650 address space.
2651
2652 @item MCL_FUTURE
2653 Set a mode such that any pages added to the process' virtual address
2654 space in the future will be locked from birth. This mode does not
2655 affect future address spaces owned by the same process so exec, which
2656 replaces a process' address space, wipes out @code{MCL_FUTURE}.
2657 @xref{Executing a File}.
2658
2659 @end table
2660
2661 When the function returns successfully, and you specified
2662 @code{MCL_CURRENT}, all of the process' pages are backed by (connected
2663 to) real frames (they are resident) and are marked to stay that way.
2664 This means the function may cause page-ins and have to wait for them.
2665
2666 When the process is in @code{MCL_FUTURE} mode because it successfully
2667 executed this function and specified @code{MCL_CURRENT}, any system call
2668 by the process that requires space be added to its virtual address space
2669 fails with @code{errno} = @code{ENOMEM} if locking the additional space
2670 would cause the process to exceed its locked page limit. In the case
2671 that the address space addition that can't be accommodated is stack
2672 expansion, the stack expansion fails and the kernel sends a
2673 @code{SIGSEGV} signal to the process.
2674
2675 When the function fails, it does not affect the lock status of any pages
2676 or the future locking mode.
2677
2678 The return value is zero if the function succeeds. Otherwise, it is
2679 @code{-1} and @code{errno} is set accordingly. @code{errno} values
2680 specific to this function are:
2681
2682 @table @code
2683 @item ENOMEM
2684 @itemize @bullet
2685 @item
2686 At least some of the specified address range does not exist in the
2687 calling process' virtual address space.
2688 @item
2689 The locking would cause the process to exceed its locked page limit.
2690 @end itemize
2691
2692 @item EPERM
2693 The calling process is not superuser.
2694
2695 @item EINVAL
2696 Undefined bits in @var{flags} are not zero.
2697
2698 @item ENOSYS
2699 The kernel does not provide @code{mlockall} capability.
2700
2701 @end table
2702
2703 You can lock just specific pages with @code{mlock}. You unlock pages
2704 with @code{munlockall} and @code{munlock}.
2705
2706 @end deftypefun
2707
2708
2709 @comment sys/mman.h
2710 @comment POSIX.1b
2711 @deftypefun int munlockall (void)
2712
2713 @code{munlockall} unlocks every page in the calling process' virtual
2714 address space and turn off @code{MCL_FUTURE} future locking mode.
2715
2716 The return value is zero if the function succeeds. Otherwise, it is
2717 @code{-1} and @code{errno} is set accordingly. The only way this
2718 function can fail is for generic reasons that all functions and system
2719 calls can fail, so there are no specific @code{errno} values.
2720
2721 @end deftypefun
2722
2723
2724
2725
2726 @ignore
2727 @c This was never actually implemented. -zw
2728 @node Relocating Allocator
2729 @section Relocating Allocator
2730
2731 @cindex relocating memory allocator
2732 Any system of dynamic memory allocation has overhead: the amount of
2733 space it uses is more than the amount the program asks for. The
2734 @dfn{relocating memory allocator} achieves very low overhead by moving
2735 blocks in memory as necessary, on its own initiative.
2736
2737 @c @menu
2738 @c * Relocator Concepts:: How to understand relocating allocation.
2739 @c * Using Relocator:: Functions for relocating allocation.
2740 @c @end menu
2741
2742 @node Relocator Concepts
2743 @subsection Concepts of Relocating Allocation
2744
2745 @ifinfo
2746 The @dfn{relocating memory allocator} achieves very low overhead by
2747 moving blocks in memory as necessary, on its own initiative.
2748 @end ifinfo
2749
2750 When you allocate a block with @code{malloc}, the address of the block
2751 never changes unless you use @code{realloc} to change its size. Thus,
2752 you can safely store the address in various places, temporarily or
2753 permanently, as you like. This is not safe when you use the relocating
2754 memory allocator, because any and all relocatable blocks can move
2755 whenever you allocate memory in any fashion. Even calling @code{malloc}
2756 or @code{realloc} can move the relocatable blocks.
2757
2758 @cindex handle
2759 For each relocatable block, you must make a @dfn{handle}---a pointer
2760 object in memory, designated to store the address of that block. The
2761 relocating allocator knows where each block's handle is, and updates the
2762 address stored there whenever it moves the block, so that the handle
2763 always points to the block. Each time you access the contents of the
2764 block, you should fetch its address anew from the handle.
2765
2766 To call any of the relocating allocator functions from a signal handler
2767 is almost certainly incorrect, because the signal could happen at any
2768 time and relocate all the blocks. The only way to make this safe is to
2769 block the signal around any access to the contents of any relocatable
2770 block---not a convenient mode of operation. @xref{Nonreentrancy}.
2771
2772 @node Using Relocator
2773 @subsection Allocating and Freeing Relocatable Blocks
2774
2775 @pindex malloc.h
2776 In the descriptions below, @var{handleptr} designates the address of the
2777 handle. All the functions are declared in @file{malloc.h}; all are GNU
2778 extensions.
2779
2780 @comment malloc.h
2781 @comment GNU
2782 @c @deftypefun {void *} r_alloc (void **@var{handleptr}, size_t @var{size})
2783 This function allocates a relocatable block of size @var{size}. It
2784 stores the block's address in @code{*@var{handleptr}} and returns
2785 a non-null pointer to indicate success.
2786
2787 If @code{r_alloc} can't get the space needed, it stores a null pointer
2788 in @code{*@var{handleptr}}, and returns a null pointer.
2789 @end deftypefun
2790
2791 @comment malloc.h
2792 @comment GNU
2793 @c @deftypefun void r_alloc_free (void **@var{handleptr})
2794 This function is the way to free a relocatable block. It frees the
2795 block that @code{*@var{handleptr}} points to, and stores a null pointer
2796 in @code{*@var{handleptr}} to show it doesn't point to an allocated
2797 block any more.
2798 @end deftypefun
2799
2800 @comment malloc.h
2801 @comment GNU
2802 @c @deftypefun {void *} r_re_alloc (void **@var{handleptr}, size_t @var{size})
2803 The function @code{r_re_alloc} adjusts the size of the block that
2804 @code{*@var{handleptr}} points to, making it @var{size} bytes long. It
2805 stores the address of the resized block in @code{*@var{handleptr}} and
2806 returns a non-null pointer to indicate success.
2807
2808 If enough memory is not available, this function returns a null pointer
2809 and does not modify @code{*@var{handleptr}}.
2810 @end deftypefun
2811 @end ignore
2812
2813
2814
2815
2816 @ignore
2817 @comment No longer available...
2818
2819 @comment @node Memory Warnings
2820 @comment @section Memory Usage Warnings
2821 @comment @cindex memory usage warnings
2822 @comment @cindex warnings of memory almost full
2823
2824 @pindex malloc.c
2825 You can ask for warnings as the program approaches running out of memory
2826 space, by calling @code{memory_warnings}. This tells @code{malloc} to
2827 check memory usage every time it asks for more memory from the operating
2828 system. This is a GNU extension declared in @file{malloc.h}.
2829
2830 @comment malloc.h
2831 @comment GNU
2832 @comment @deftypefun void memory_warnings (void *@var{start}, void (*@var{warn-func}) (const char *))
2833 Call this function to request warnings for nearing exhaustion of virtual
2834 memory.
2835
2836 The argument @var{start} says where data space begins, in memory. The
2837 allocator compares this against the last address used and against the
2838 limit of data space, to determine the fraction of available memory in
2839 use. If you supply zero for @var{start}, then a default value is used
2840 which is right in most circumstances.
2841
2842 For @var{warn-func}, supply a function that @code{malloc} can call to
2843 warn you. It is called with a string (a warning message) as argument.
2844 Normally it ought to display the string for the user to read.
2845 @end deftypefun
2846
2847 The warnings come when memory becomes 75% full, when it becomes 85%
2848 full, and when it becomes 95% full. Above 95% you get another warning
2849 each time memory usage increases.
2850
2851 @end ignore