S390: Move utf8-utf32-z9.c to multiarch folder and use s390_libc_ifunc_expr macro.
[glibc.git] / manual / string.texi
blobb8810d66b763dab3c431a38c083b8cb2cfac2da8
1 @node String and Array Utilities, Character Set Handling, Character Handling, Top
2 @c %MENU% Utilities for copying and comparing strings and arrays
3 @chapter String and Array Utilities
5 Operations on strings (null-terminated byte sequences) are an important part of
6 many programs.  @Theglibc{} provides an extensive set of string
7 utility functions, including functions for copying, concatenating,
8 comparing, and searching strings.  Many of these functions can also
9 operate on arbitrary regions of storage; for example, the @code{memcpy}
10 function can be used to copy the contents of any kind of array.
12 It's fairly common for beginning C programmers to ``reinvent the wheel''
13 by duplicating this functionality in their own code, but it pays to
14 become familiar with the library functions and to make use of them,
15 since this offers benefits in maintenance, efficiency, and portability.
17 For instance, you could easily compare one string to another in two
18 lines of C code, but if you use the built-in @code{strcmp} function,
19 you're less likely to make a mistake.  And, since these library
20 functions are typically highly optimized, your program may run faster
21 too.
23 @menu
24 * Representation of Strings::   Introduction to basic concepts.
25 * String/Array Conventions::    Whether to use a string function or an
26                                  arbitrary array function.
27 * String Length::               Determining the length of a string.
28 * Copying Strings and Arrays::  Functions to copy strings and arrays.
29 * Concatenating Strings::       Functions to concatenate strings while copying.
30 * Truncating Strings::          Functions to truncate strings while copying.
31 * String/Array Comparison::     Functions for byte-wise and character-wise
32                                  comparison.
33 * Collation Functions::         Functions for collating strings.
34 * Search Functions::            Searching for a specific element or substring.
35 * Finding Tokens in a String::  Splitting a string into tokens by looking
36                                  for delimiters.
37 * Erasing Sensitive Data::      Clearing memory which contains sensitive
38                                  data, after it's no longer needed.
39 * strfry::                      Function for flash-cooking a string.
40 * Trivial Encryption::          Obscuring data.
41 * Encode Binary Data::          Encoding and Decoding of Binary Data.
42 * Argz and Envz Vectors::       Null-separated string vectors.
43 @end menu
45 @node Representation of Strings
46 @section Representation of Strings
47 @cindex string, representation of
49 This section is a quick summary of string concepts for beginning C
50 programmers.  It describes how strings are represented in C
51 and some common pitfalls.  If you are already familiar with this
52 material, you can skip this section.
54 @cindex string
55 A @dfn{string} is a null-terminated array of bytes of type @code{char},
56 including the terminating null byte.  String-valued
57 variables are usually declared to be pointers of type @code{char *}.
58 Such variables do not include space for the text of a string; that has
59 to be stored somewhere else---in an array variable, a string constant,
60 or dynamically allocated memory (@pxref{Memory Allocation}).  It's up to
61 you to store the address of the chosen memory space into the pointer
62 variable.  Alternatively you can store a @dfn{null pointer} in the
63 pointer variable.  The null pointer does not point anywhere, so
64 attempting to reference the string it points to gets an error.
66 @cindex multibyte character
67 @cindex multibyte string
68 @cindex wide string
69 A @dfn{multibyte character} is a sequence of one or more bytes that
70 represents a single character using the locale's encoding scheme; a
71 null byte always represents the null character.  A @dfn{multibyte
72 string} is a string that consists entirely of multibyte
73 characters.  In contrast, a @dfn{wide string} is a null-terminated
74 sequence of @code{wchar_t} objects.  A wide-string variable is usually
75 declared to be a pointer of type @code{wchar_t *}, by analogy with
76 string variables and @code{char *}.  @xref{Extended Char Intro}.
78 @cindex null byte
79 @cindex null wide character
80 By convention, the @dfn{null byte}, @code{'\0'},
81 marks the end of a string and the @dfn{null wide character},
82 @code{L'\0'}, marks the end of a wide string.  For example, in
83 testing to see whether the @code{char *} variable @var{p} points to a
84 null byte marking the end of a string, you can write
85 @code{!*@var{p}} or @code{*@var{p} == '\0'}.
87 A null byte is quite different conceptually from a null pointer,
88 although both are represented by the integer constant @code{0}.
90 @cindex string literal
91 A @dfn{string literal} appears in C program source as a multibyte
92 string between double-quote characters (@samp{"}).  If the
93 initial double-quote character is immediately preceded by a capital
94 @samp{L} (ell) character (as in @code{L"foo"}), it is a wide string
95 literal.  String literals can also contribute to @dfn{string
96 concatenation}: @code{"a" "b"} is the same as @code{"ab"}.
97 For wide strings one can use either
98 @code{L"a" L"b"} or @code{L"a" "b"}.  Modification of string literals is
99 not allowed by the GNU C compiler, because literals are placed in
100 read-only storage.
102 Arrays that are declared @code{const} cannot be modified
103 either.  It's generally good style to declare non-modifiable string
104 pointers to be of type @code{const char *}, since this often allows the
105 C compiler to detect accidental modifications as well as providing some
106 amount of documentation about what your program intends to do with the
107 string.
109 The amount of memory allocated for a byte array may extend past the null byte
110 that marks the end of the string that the array contains.  In this
111 document, the term @dfn{allocated size} is always used to refer to the
112 total amount of memory allocated for an array, while the term
113 @dfn{length} refers to the number of bytes up to (but not including)
114 the terminating null byte.  Wide strings are similar, except their
115 sizes and lengths count wide characters, not bytes.
116 @cindex length of string
117 @cindex allocation size of string
118 @cindex size of string
119 @cindex string length
120 @cindex string allocation
122 A notorious source of program bugs is trying to put more bytes into a
123 string than fit in its allocated size.  When writing code that extends
124 strings or moves bytes into a pre-allocated array, you should be
125 very careful to keep track of the length of the text and make explicit
126 checks for overflowing the array.  Many of the library functions
127 @emph{do not} do this for you!  Remember also that you need to allocate
128 an extra byte to hold the null byte that marks the end of the
129 string.
131 @cindex single-byte string
132 @cindex multibyte string
133 Originally strings were sequences of bytes where each byte represented a
134 single character.  This is still true today if the strings are encoded
135 using a single-byte character encoding.  Things are different if the
136 strings are encoded using a multibyte encoding (for more information on
137 encodings see @ref{Extended Char Intro}).  There is no difference in
138 the programming interface for these two kind of strings; the programmer
139 has to be aware of this and interpret the byte sequences accordingly.
141 But since there is no separate interface taking care of these
142 differences the byte-based string functions are sometimes hard to use.
143 Since the count parameters of these functions specify bytes a call to
144 @code{memcpy} could cut a multibyte character in the middle and put an
145 incomplete (and therefore unusable) byte sequence in the target buffer.
147 @cindex wide string
148 To avoid these problems later versions of the @w{ISO C} standard
149 introduce a second set of functions which are operating on @dfn{wide
150 characters} (@pxref{Extended Char Intro}).  These functions don't have
151 the problems the single-byte versions have since every wide character is
152 a legal, interpretable value.  This does not mean that cutting wide
153 strings at arbitrary points is without problems.  It normally
154 is for alphabet-based languages (except for non-normalized text) but
155 languages based on syllables still have the problem that more than one
156 wide character is necessary to complete a logical unit.  This is a
157 higher level problem which the @w{C library} functions are not designed
158 to solve.  But it is at least good that no invalid byte sequences can be
159 created.  Also, the higher level functions can also much more easily operate
160 on wide characters than on multibyte characters so that a common strategy
161 is to use wide characters internally whenever text is more than simply
162 copied.
164 The remaining of this chapter will discuss the functions for handling
165 wide strings in parallel with the discussion of
166 strings since there is almost always an exact equivalent
167 available.
169 @node String/Array Conventions
170 @section String and Array Conventions
172 This chapter describes both functions that work on arbitrary arrays or
173 blocks of memory, and functions that are specific to strings and wide
174 strings.
176 Functions that operate on arbitrary blocks of memory have names
177 beginning with @samp{mem} and @samp{wmem} (such as @code{memcpy} and
178 @code{wmemcpy}) and invariably take an argument which specifies the size
179 (in bytes and wide characters respectively) of the block of memory to
180 operate on.  The array arguments and return values for these functions
181 have type @code{void *} or @code{wchar_t}.  As a matter of style, the
182 elements of the arrays used with the @samp{mem} functions are referred
183 to as ``bytes''.  You can pass any kind of pointer to these functions,
184 and the @code{sizeof} operator is useful in computing the value for the
185 size argument.  Parameters to the @samp{wmem} functions must be of type
186 @code{wchar_t *}.  These functions are not really usable with anything
187 but arrays of this type.
189 In contrast, functions that operate specifically on strings and wide
190 strings have names beginning with @samp{str} and @samp{wcs}
191 respectively (such as @code{strcpy} and @code{wcscpy}) and look for a
192 terminating null byte or null wide character instead of requiring an explicit
193 size argument to be passed.  (Some of these functions accept a specified
194 maximum length, but they also check for premature termination.)
195 The array arguments and return values for these
196 functions have type @code{char *} and @code{wchar_t *} respectively, and
197 the array elements are referred to as ``bytes'' and ``wide
198 characters''.
200 In many cases, there are both @samp{mem} and @samp{str}/@samp{wcs}
201 versions of a function.  The one that is more appropriate to use depends
202 on the exact situation.  When your program is manipulating arbitrary
203 arrays or blocks of storage, then you should always use the @samp{mem}
204 functions.  On the other hand, when you are manipulating
205 strings it is usually more convenient to use the @samp{str}/@samp{wcs}
206 functions, unless you already know the length of the string in advance.
207 The @samp{wmem} functions should be used for wide character arrays with
208 known size.
210 @cindex wint_t
211 @cindex parameter promotion
212 Some of the memory and string functions take single characters as
213 arguments.  Since a value of type @code{char} is automatically promoted
214 into a value of type @code{int} when used as a parameter, the functions
215 are declared with @code{int} as the type of the parameter in question.
216 In case of the wide character functions the situation is similar: the
217 parameter type for a single wide character is @code{wint_t} and not
218 @code{wchar_t}.  This would for many implementations not be necessary
219 since @code{wchar_t} is large enough to not be automatically
220 promoted, but since the @w{ISO C} standard does not require such a
221 choice of types the @code{wint_t} type is used.
223 @node String Length
224 @section String Length
226 You can get the length of a string using the @code{strlen} function.
227 This function is declared in the header file @file{string.h}.
228 @pindex string.h
230 @comment string.h
231 @comment ISO
232 @deftypefun size_t strlen (const char *@var{s})
233 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
234 The @code{strlen} function returns the length of the
235 string @var{s} in bytes.  (In other words, it returns the offset of the
236 terminating null byte within the array.)
238 For example,
239 @smallexample
240 strlen ("hello, world")
241     @result{} 12
242 @end smallexample
244 When applied to an array, the @code{strlen} function returns
245 the length of the string stored there, not its allocated size.  You can
246 get the allocated size of the array that holds a string using
247 the @code{sizeof} operator:
249 @smallexample
250 char string[32] = "hello, world";
251 sizeof (string)
252     @result{} 32
253 strlen (string)
254     @result{} 12
255 @end smallexample
257 But beware, this will not work unless @var{string} is the
258 array itself, not a pointer to it.  For example:
260 @smallexample
261 char string[32] = "hello, world";
262 char *ptr = string;
263 sizeof (string)
264     @result{} 32
265 sizeof (ptr)
266     @result{} 4  /* @r{(on a machine with 4 byte pointers)} */
267 @end smallexample
269 This is an easy mistake to make when you are working with functions that
270 take string arguments; those arguments are always pointers, not arrays.
272 It must also be noted that for multibyte encoded strings the return
273 value does not have to correspond to the number of characters in the
274 string.  To get this value the string can be converted to wide
275 characters and @code{wcslen} can be used or something like the following
276 code can be used:
278 @smallexample
279 /* @r{The input is in @code{string}.}
280    @r{The length is expected in @code{n}.}  */
282   mbstate_t t;
283   char *scopy = string;
284   /* In initial state.  */
285   memset (&t, '\0', sizeof (t));
286   /* Determine number of characters.  */
287   n = mbsrtowcs (NULL, &scopy, strlen (scopy), &t);
289 @end smallexample
291 This is cumbersome to do so if the number of characters (as opposed to
292 bytes) is needed often it is better to work with wide characters.
293 @end deftypefun
295 The wide character equivalent is declared in @file{wchar.h}.
297 @comment wchar.h
298 @comment ISO
299 @deftypefun size_t wcslen (const wchar_t *@var{ws})
300 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
301 The @code{wcslen} function is the wide character equivalent to
302 @code{strlen}.  The return value is the number of wide characters in the
303 wide string pointed to by @var{ws} (this is also the offset of
304 the terminating null wide character of @var{ws}).
306 Since there are no multi wide character sequences making up one wide
307 character the return value is not only the offset in the array, it is
308 also the number of wide characters.
310 This function was introduced in @w{Amendment 1} to @w{ISO C90}.
311 @end deftypefun
313 @comment string.h
314 @comment GNU
315 @deftypefun size_t strnlen (const char *@var{s}, size_t @var{maxlen})
316 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
317 If the array @var{s} of size @var{maxlen} contains a null byte,
318 the @code{strnlen} function returns the length of the string @var{s} in
319 bytes.  Otherwise it
320 returns @var{maxlen}.  Therefore this function is equivalent to
321 @code{(strlen (@var{s}) < @var{maxlen} ? strlen (@var{s}) : @var{maxlen})}
322 but it
323 is more efficient and works even if @var{s} is not null-terminated so
324 long as @var{maxlen} does not exceed the size of @var{s}'s array.
326 @smallexample
327 char string[32] = "hello, world";
328 strnlen (string, 32)
329     @result{} 12
330 strnlen (string, 5)
331     @result{} 5
332 @end smallexample
334 This function is a GNU extension and is declared in @file{string.h}.
335 @end deftypefun
337 @comment wchar.h
338 @comment GNU
339 @deftypefun size_t wcsnlen (const wchar_t *@var{ws}, size_t @var{maxlen})
340 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
341 @code{wcsnlen} is the wide character equivalent to @code{strnlen}.  The
342 @var{maxlen} parameter specifies the maximum number of wide characters.
344 This function is a GNU extension and is declared in @file{wchar.h}.
345 @end deftypefun
347 @node Copying Strings and Arrays
348 @section Copying Strings and Arrays
350 You can use the functions described in this section to copy the contents
351 of strings, wide strings, and arrays.  The @samp{str} and @samp{mem}
352 functions are declared in @file{string.h} while the @samp{w} functions
353 are declared in @file{wchar.h}.
354 @pindex string.h
355 @pindex wchar.h
356 @cindex copying strings and arrays
357 @cindex string copy functions
358 @cindex array copy functions
359 @cindex concatenating strings
360 @cindex string concatenation functions
362 A helpful way to remember the ordering of the arguments to the functions
363 in this section is that it corresponds to an assignment expression, with
364 the destination array specified to the left of the source array.  Most
365 of these functions return the address of the destination array; a few
366 return the address of the destination's terminating null, or of just
367 past the destination.
369 Most of these functions do not work properly if the source and
370 destination arrays overlap.  For example, if the beginning of the
371 destination array overlaps the end of the source array, the original
372 contents of that part of the source array may get overwritten before it
373 is copied.  Even worse, in the case of the string functions, the null
374 byte marking the end of the string may be lost, and the copy
375 function might get stuck in a loop trashing all the memory allocated to
376 your program.
378 All functions that have problems copying between overlapping arrays are
379 explicitly identified in this manual.  In addition to functions in this
380 section, there are a few others like @code{sprintf} (@pxref{Formatted
381 Output Functions}) and @code{scanf} (@pxref{Formatted Input
382 Functions}).
384 @comment string.h
385 @comment ISO
386 @deftypefun {void *} memcpy (void *restrict @var{to}, const void *restrict @var{from}, size_t @var{size})
387 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
388 The @code{memcpy} function copies @var{size} bytes from the object
389 beginning at @var{from} into the object beginning at @var{to}.  The
390 behavior of this function is undefined if the two arrays @var{to} and
391 @var{from} overlap; use @code{memmove} instead if overlapping is possible.
393 The value returned by @code{memcpy} is the value of @var{to}.
395 Here is an example of how you might use @code{memcpy} to copy the
396 contents of an array:
398 @smallexample
399 struct foo *oldarray, *newarray;
400 int arraysize;
401 @dots{}
402 memcpy (new, old, arraysize * sizeof (struct foo));
403 @end smallexample
404 @end deftypefun
406 @comment wchar.h
407 @comment ISO
408 @deftypefun {wchar_t *} wmemcpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
409 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
410 The @code{wmemcpy} function copies @var{size} wide characters from the object
411 beginning at @var{wfrom} into the object beginning at @var{wto}.  The
412 behavior of this function is undefined if the two arrays @var{wto} and
413 @var{wfrom} overlap; use @code{wmemmove} instead if overlapping is possible.
415 The following is a possible implementation of @code{wmemcpy} but there
416 are more optimizations possible.
418 @smallexample
419 wchar_t *
420 wmemcpy (wchar_t *restrict wto, const wchar_t *restrict wfrom,
421          size_t size)
423   return (wchar_t *) memcpy (wto, wfrom, size * sizeof (wchar_t));
425 @end smallexample
427 The value returned by @code{wmemcpy} is the value of @var{wto}.
429 This function was introduced in @w{Amendment 1} to @w{ISO C90}.
430 @end deftypefun
432 @comment string.h
433 @comment GNU
434 @deftypefun {void *} mempcpy (void *restrict @var{to}, const void *restrict @var{from}, size_t @var{size})
435 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
436 The @code{mempcpy} function is nearly identical to the @code{memcpy}
437 function.  It copies @var{size} bytes from the object beginning at
438 @code{from} into the object pointed to by @var{to}.  But instead of
439 returning the value of @var{to} it returns a pointer to the byte
440 following the last written byte in the object beginning at @var{to}.
441 I.e., the value is @code{((void *) ((char *) @var{to} + @var{size}))}.
443 This function is useful in situations where a number of objects shall be
444 copied to consecutive memory positions.
446 @smallexample
447 void *
448 combine (void *o1, size_t s1, void *o2, size_t s2)
450   void *result = malloc (s1 + s2);
451   if (result != NULL)
452     mempcpy (mempcpy (result, o1, s1), o2, s2);
453   return result;
455 @end smallexample
457 This function is a GNU extension.
458 @end deftypefun
460 @comment wchar.h
461 @comment GNU
462 @deftypefun {wchar_t *} wmempcpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
463 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
464 The @code{wmempcpy} function is nearly identical to the @code{wmemcpy}
465 function.  It copies @var{size} wide characters from the object
466 beginning at @code{wfrom} into the object pointed to by @var{wto}.  But
467 instead of returning the value of @var{wto} it returns a pointer to the
468 wide character following the last written wide character in the object
469 beginning at @var{wto}.  I.e., the value is @code{@var{wto} + @var{size}}.
471 This function is useful in situations where a number of objects shall be
472 copied to consecutive memory positions.
474 The following is a possible implementation of @code{wmemcpy} but there
475 are more optimizations possible.
477 @smallexample
478 wchar_t *
479 wmempcpy (wchar_t *restrict wto, const wchar_t *restrict wfrom,
480           size_t size)
482   return (wchar_t *) mempcpy (wto, wfrom, size * sizeof (wchar_t));
484 @end smallexample
486 This function is a GNU extension.
487 @end deftypefun
489 @comment string.h
490 @comment ISO
491 @deftypefun {void *} memmove (void *@var{to}, const void *@var{from}, size_t @var{size})
492 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
493 @code{memmove} copies the @var{size} bytes at @var{from} into the
494 @var{size} bytes at @var{to}, even if those two blocks of space
495 overlap.  In the case of overlap, @code{memmove} is careful to copy the
496 original values of the bytes in the block at @var{from}, including those
497 bytes which also belong to the block at @var{to}.
499 The value returned by @code{memmove} is the value of @var{to}.
500 @end deftypefun
502 @comment wchar.h
503 @comment ISO
504 @deftypefun {wchar_t *} wmemmove (wchar_t *@var{wto}, const wchar_t *@var{wfrom}, size_t @var{size})
505 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
506 @code{wmemmove} copies the @var{size} wide characters at @var{wfrom}
507 into the @var{size} wide characters at @var{wto}, even if those two
508 blocks of space overlap.  In the case of overlap, @code{wmemmove} is
509 careful to copy the original values of the wide characters in the block
510 at @var{wfrom}, including those wide characters which also belong to the
511 block at @var{wto}.
513 The following is a possible implementation of @code{wmemcpy} but there
514 are more optimizations possible.
516 @smallexample
517 wchar_t *
518 wmempcpy (wchar_t *restrict wto, const wchar_t *restrict wfrom,
519           size_t size)
521   return (wchar_t *) mempcpy (wto, wfrom, size * sizeof (wchar_t));
523 @end smallexample
525 The value returned by @code{wmemmove} is the value of @var{wto}.
527 This function is a GNU extension.
528 @end deftypefun
530 @comment string.h
531 @comment SVID
532 @deftypefun {void *} memccpy (void *restrict @var{to}, const void *restrict @var{from}, int @var{c}, size_t @var{size})
533 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
534 This function copies no more than @var{size} bytes from @var{from} to
535 @var{to}, stopping if a byte matching @var{c} is found.  The return
536 value is a pointer into @var{to} one byte past where @var{c} was copied,
537 or a null pointer if no byte matching @var{c} appeared in the first
538 @var{size} bytes of @var{from}.
539 @end deftypefun
541 @comment string.h
542 @comment ISO
543 @deftypefun {void *} memset (void *@var{block}, int @var{c}, size_t @var{size})
544 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
545 This function copies the value of @var{c} (converted to an
546 @code{unsigned char}) into each of the first @var{size} bytes of the
547 object beginning at @var{block}.  It returns the value of @var{block}.
548 @end deftypefun
550 @comment wchar.h
551 @comment ISO
552 @deftypefun {wchar_t *} wmemset (wchar_t *@var{block}, wchar_t @var{wc}, size_t @var{size})
553 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
554 This function copies the value of @var{wc} into each of the first
555 @var{size} wide characters of the object beginning at @var{block}.  It
556 returns the value of @var{block}.
557 @end deftypefun
559 @comment string.h
560 @comment ISO
561 @deftypefun {char *} strcpy (char *restrict @var{to}, const char *restrict @var{from})
562 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
563 This copies bytes from the string @var{from} (up to and including
564 the terminating null byte) into the string @var{to}.  Like
565 @code{memcpy}, this function has undefined results if the strings
566 overlap.  The return value is the value of @var{to}.
567 @end deftypefun
569 @comment wchar.h
570 @comment ISO
571 @deftypefun {wchar_t *} wcscpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom})
572 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
573 This copies wide characters from the wide string @var{wfrom} (up to and
574 including the terminating null wide character) into the string
575 @var{wto}.  Like @code{wmemcpy}, this function has undefined results if
576 the strings overlap.  The return value is the value of @var{wto}.
577 @end deftypefun
579 @comment SVID
580 @deftypefun {char *} strdup (const char *@var{s})
581 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
582 This function copies the string @var{s} into a newly
583 allocated string.  The string is allocated using @code{malloc}; see
584 @ref{Unconstrained Allocation}.  If @code{malloc} cannot allocate space
585 for the new string, @code{strdup} returns a null pointer.  Otherwise it
586 returns a pointer to the new string.
587 @end deftypefun
589 @comment wchar.h
590 @comment GNU
591 @deftypefun {wchar_t *} wcsdup (const wchar_t *@var{ws})
592 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
593 This function copies the wide string @var{ws}
594 into a newly allocated string.  The string is allocated using
595 @code{malloc}; see @ref{Unconstrained Allocation}.  If @code{malloc}
596 cannot allocate space for the new string, @code{wcsdup} returns a null
597 pointer.  Otherwise it returns a pointer to the new wide string.
599 This function is a GNU extension.
600 @end deftypefun
602 @comment string.h
603 @comment Unknown origin
604 @deftypefun {char *} stpcpy (char *restrict @var{to}, const char *restrict @var{from})
605 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
606 This function is like @code{strcpy}, except that it returns a pointer to
607 the end of the string @var{to} (that is, the address of the terminating
608 null byte @code{to + strlen (from)}) rather than the beginning.
610 For example, this program uses @code{stpcpy} to concatenate @samp{foo}
611 and @samp{bar} to produce @samp{foobar}, which it then prints.
613 @smallexample
614 @include stpcpy.c.texi
615 @end smallexample
617 This function is part of POSIX.1-2008 and later editions, but was
618 available in @theglibc{} and other systems as an extension long before
619 it was standardized.
621 Its behavior is undefined if the strings overlap.  The function is
622 declared in @file{string.h}.
623 @end deftypefun
625 @comment wchar.h
626 @comment GNU
627 @deftypefun {wchar_t *} wcpcpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom})
628 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
629 This function is like @code{wcscpy}, except that it returns a pointer to
630 the end of the string @var{wto} (that is, the address of the terminating
631 null wide character @code{wto + wcslen (wfrom)}) rather than the beginning.
633 This function is not part of ISO or POSIX but was found useful while
634 developing @theglibc{} itself.
636 The behavior of @code{wcpcpy} is undefined if the strings overlap.
638 @code{wcpcpy} is a GNU extension and is declared in @file{wchar.h}.
639 @end deftypefun
641 @comment string.h
642 @comment GNU
643 @deftypefn {Macro} {char *} strdupa (const char *@var{s})
644 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
645 This macro is similar to @code{strdup} but allocates the new string
646 using @code{alloca} instead of @code{malloc} (@pxref{Variable Size
647 Automatic}).  This means of course the returned string has the same
648 limitations as any block of memory allocated using @code{alloca}.
650 For obvious reasons @code{strdupa} is implemented only as a macro;
651 you cannot get the address of this function.  Despite this limitation
652 it is a useful function.  The following code shows a situation where
653 using @code{malloc} would be a lot more expensive.
655 @smallexample
656 @include strdupa.c.texi
657 @end smallexample
659 Please note that calling @code{strtok} using @var{path} directly is
660 invalid.  It is also not allowed to call @code{strdupa} in the argument
661 list of @code{strtok} since @code{strdupa} uses @code{alloca}
662 (@pxref{Variable Size Automatic}) can interfere with the parameter
663 passing.
665 This function is only available if GNU CC is used.
666 @end deftypefn
668 @comment string.h
669 @comment BSD
670 @deftypefun void bcopy (const void *@var{from}, void *@var{to}, size_t @var{size})
671 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
672 This is a partially obsolete alternative for @code{memmove}, derived from
673 BSD.  Note that it is not quite equivalent to @code{memmove}, because the
674 arguments are not in the same order and there is no return value.
675 @end deftypefun
677 @comment string.h
678 @comment BSD
679 @deftypefun void bzero (void *@var{block}, size_t @var{size})
680 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
681 This is a partially obsolete alternative for @code{memset}, derived from
682 BSD.  Note that it is not as general as @code{memset}, because the only
683 value it can store is zero.
684 @end deftypefun
686 @node Concatenating Strings
687 @section Concatenating Strings
688 @pindex string.h
689 @pindex wchar.h
690 @cindex concatenating strings
691 @cindex string concatenation functions
693 The functions described in this section concatenate the contents of a
694 string or wide string to another.  They follow the string-copying
695 functions in their conventions.  @xref{Copying Strings and Arrays}.
696 @samp{strcat} is declared in the header file @file{string.h} while
697 @samp{wcscat} is declared in @file{wchar.h}.
699 @comment string.h
700 @comment ISO
701 @deftypefun {char *} strcat (char *restrict @var{to}, const char *restrict @var{from})
702 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
703 The @code{strcat} function is similar to @code{strcpy}, except that the
704 bytes from @var{from} are concatenated or appended to the end of
705 @var{to}, instead of overwriting it.  That is, the first byte from
706 @var{from} overwrites the null byte marking the end of @var{to}.
708 An equivalent definition for @code{strcat} would be:
710 @smallexample
711 char *
712 strcat (char *restrict to, const char *restrict from)
714   strcpy (to + strlen (to), from);
715   return to;
717 @end smallexample
719 This function has undefined results if the strings overlap.
721 As noted below, this function has significant performance issues.
722 @end deftypefun
724 @comment wchar.h
725 @comment ISO
726 @deftypefun {wchar_t *} wcscat (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom})
727 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
728 The @code{wcscat} function is similar to @code{wcscpy}, except that the
729 wide characters from @var{wfrom} are concatenated or appended to the end of
730 @var{wto}, instead of overwriting it.  That is, the first wide character from
731 @var{wfrom} overwrites the null wide character marking the end of @var{wto}.
733 An equivalent definition for @code{wcscat} would be:
735 @smallexample
736 wchar_t *
737 wcscat (wchar_t *wto, const wchar_t *wfrom)
739   wcscpy (wto + wcslen (wto), wfrom);
740   return wto;
742 @end smallexample
744 This function has undefined results if the strings overlap.
746 As noted below, this function has significant performance issues.
747 @end deftypefun
749 Programmers using the @code{strcat} or @code{wcscat} function (or the
750 @code{strncat} or @code{wcsncat} functions defined in
751 a later section, for that matter)
752 can easily be recognized as lazy and reckless.  In almost all situations
753 the lengths of the participating strings are known (it better should be
754 since how can one otherwise ensure the allocated size of the buffer is
755 sufficient?)  Or at least, one could know them if one keeps track of the
756 results of the various function calls.  But then it is very inefficient
757 to use @code{strcat}/@code{wcscat}.  A lot of time is wasted finding the
758 end of the destination string so that the actual copying can start.
759 This is a common example:
761 @cindex va_copy
762 @smallexample
763 /* @r{This function concatenates arbitrarily many strings.  The last}
764    @r{parameter must be @code{NULL}.}  */
765 char *
766 concat (const char *str, @dots{})
768   va_list ap, ap2;
769   size_t total = 1;
770   const char *s;
771   char *result;
773   va_start (ap, str);
774   va_copy (ap2, ap);
776   /* @r{Determine how much space we need.}  */
777   for (s = str; s != NULL; s = va_arg (ap, const char *))
778     total += strlen (s);
780   va_end (ap);
782   result = (char *) malloc (total);
783   if (result != NULL)
784     @{
785       result[0] = '\0';
787       /* @r{Copy the strings.}  */
788       for (s = str; s != NULL; s = va_arg (ap2, const char *))
789         strcat (result, s);
790     @}
792   va_end (ap2);
794   return result;
796 @end smallexample
798 This looks quite simple, especially the second loop where the strings
799 are actually copied.  But these innocent lines hide a major performance
800 penalty.  Just imagine that ten strings of 100 bytes each have to be
801 concatenated.  For the second string we search the already stored 100
802 bytes for the end of the string so that we can append the next string.
803 For all strings in total the comparisons necessary to find the end of
804 the intermediate results sums up to 5500!  If we combine the copying
805 with the search for the allocation we can write this function more
806 efficiently:
808 @smallexample
809 char *
810 concat (const char *str, @dots{})
812   va_list ap;
813   size_t allocated = 100;
814   char *result = (char *) malloc (allocated);
816   if (result != NULL)
817     @{
818       char *newp;
819       char *wp;
820       const char *s;
822       va_start (ap, str);
824       wp = result;
825       for (s = str; s != NULL; s = va_arg (ap, const char *))
826         @{
827           size_t len = strlen (s);
829           /* @r{Resize the allocated memory if necessary.}  */
830           if (wp + len + 1 > result + allocated)
831             @{
832               allocated = (allocated + len) * 2;
833               newp = (char *) realloc (result, allocated);
834               if (newp == NULL)
835                 @{
836                   free (result);
837                   return NULL;
838                 @}
839               wp = newp + (wp - result);
840               result = newp;
841             @}
843           wp = mempcpy (wp, s, len);
844         @}
846       /* @r{Terminate the result string.}  */
847       *wp++ = '\0';
849       /* @r{Resize memory to the optimal size.}  */
850       newp = realloc (result, wp - result);
851       if (newp != NULL)
852         result = newp;
854       va_end (ap);
855     @}
857   return result;
859 @end smallexample
861 With a bit more knowledge about the input strings one could fine-tune
862 the memory allocation.  The difference we are pointing to here is that
863 we don't use @code{strcat} anymore.  We always keep track of the length
864 of the current intermediate result so we can save ourselves the search for the
865 end of the string and use @code{mempcpy}.  Please note that we also
866 don't use @code{stpcpy} which might seem more natural since we are handling
867 strings.  But this is not necessary since we already know the
868 length of the string and therefore can use the faster memory copying
869 function.  The example would work for wide characters the same way.
871 Whenever a programmer feels the need to use @code{strcat} she or he
872 should think twice and look through the program to see whether the code cannot
873 be rewritten to take advantage of already calculated results.  Again: it
874 is almost always unnecessary to use @code{strcat}.
876 @node Truncating Strings
877 @section Truncating Strings while Copying
878 @cindex truncating strings
879 @cindex string truncation
881 The functions described in this section copy or concatenate the
882 possibly-truncated contents of a string or array to another, and
883 similarly for wide strings.  They follow the string-copying functions
884 in their header conventions.  @xref{Copying Strings and Arrays}.  The
885 @samp{str} functions are declared in the header file @file{string.h}
886 and the @samp{wc} functions are declared in the file @file{wchar.h}.
888 @comment string.h
889 @deftypefun {char *} strncpy (char *restrict @var{to}, const char *restrict @var{from}, size_t @var{size})
890 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
891 This function is similar to @code{strcpy} but always copies exactly
892 @var{size} bytes into @var{to}.
894 If @var{from} does not contain a null byte in its first @var{size}
895 bytes, @code{strncpy} copies just the first @var{size} bytes.  In this
896 case no null terminator is written into @var{to}.
898 Otherwise @var{from} must be a string with length less than
899 @var{size}.  In this case @code{strncpy} copies all of @var{from},
900 followed by enough null bytes to add up to @var{size} bytes in all.
902 The behavior of @code{strncpy} is undefined if the strings overlap.
904 This function was designed for now-rarely-used arrays consisting of
905 non-null bytes followed by zero or more null bytes.  It needs to set
906 all @var{size} bytes of the destination, even when @var{size} is much
907 greater than the length of @var{from}.  As noted below, this function
908 is generally a poor choice for processing text.
909 @end deftypefun
911 @comment wchar.h
912 @comment ISO
913 @deftypefun {wchar_t *} wcsncpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
914 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
915 This function is similar to @code{wcscpy} but always copies exactly
916 @var{size} wide characters into @var{wto}.
918 If @var{wfrom} does not contain a null wide character in its first
919 @var{size} wide characters, then @code{wcsncpy} copies just the first
920 @var{size} wide characters.  In this case no null terminator is
921 written into @var{wto}.
923 Otherwise @var{wfrom} must be a wide string with length less than
924 @var{size}.  In this case @code{wcsncpy} copies all of @var{wfrom},
925 followed by enough null wide characters to add up to @var{size} wide
926 characters in all.
928 The behavior of @code{wcsncpy} is undefined if the strings overlap.
930 This function is the wide-character counterpart of @code{strncpy} and
931 suffers from most of the problems that @code{strncpy} does.  For
932 example, as noted below, this function is generally a poor choice for
933 processing text.
934 @end deftypefun
936 @comment string.h
937 @comment GNU
938 @deftypefun {char *} strndup (const char *@var{s}, size_t @var{size})
939 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
940 This function is similar to @code{strdup} but always copies at most
941 @var{size} bytes into the newly allocated string.
943 If the length of @var{s} is more than @var{size}, then @code{strndup}
944 copies just the first @var{size} bytes and adds a closing null byte.
945 Otherwise all bytes are copied and the string is terminated.
947 This function differs from @code{strncpy} in that it always terminates
948 the destination string.
950 As noted below, this function is generally a poor choice for
951 processing text.
953 @code{strndup} is a GNU extension.
954 @end deftypefun
956 @comment string.h
957 @comment GNU
958 @deftypefn {Macro} {char *} strndupa (const char *@var{s}, size_t @var{size})
959 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
960 This function is similar to @code{strndup} but like @code{strdupa} it
961 allocates the new string using @code{alloca} @pxref{Variable Size
962 Automatic}.  The same advantages and limitations of @code{strdupa} are
963 valid for @code{strndupa}, too.
965 This function is implemented only as a macro, just like @code{strdupa}.
966 Just as @code{strdupa} this macro also must not be used inside the
967 parameter list in a function call.
969 As noted below, this function is generally a poor choice for
970 processing text.
972 @code{strndupa} is only available if GNU CC is used.
973 @end deftypefn
975 @comment string.h
976 @comment GNU
977 @deftypefun {char *} stpncpy (char *restrict @var{to}, const char *restrict @var{from}, size_t @var{size})
978 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
979 This function is similar to @code{stpcpy} but copies always exactly
980 @var{size} bytes into @var{to}.
982 If the length of @var{from} is more than @var{size}, then @code{stpncpy}
983 copies just the first @var{size} bytes and returns a pointer to the
984 byte directly following the one which was copied last.  Note that in
985 this case there is no null terminator written into @var{to}.
987 If the length of @var{from} is less than @var{size}, then @code{stpncpy}
988 copies all of @var{from}, followed by enough null bytes to add up
989 to @var{size} bytes in all.  This behavior is rarely useful, but it
990 is implemented to be useful in contexts where this behavior of the
991 @code{strncpy} is used.  @code{stpncpy} returns a pointer to the
992 @emph{first} written null byte.
994 This function is not part of ISO or POSIX but was found useful while
995 developing @theglibc{} itself.
997 Its behavior is undefined if the strings overlap.  The function is
998 declared in @file{string.h}.
1000 As noted below, this function is generally a poor choice for
1001 processing text.
1002 @end deftypefun
1004 @comment wchar.h
1005 @comment GNU
1006 @deftypefun {wchar_t *} wcpncpy (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
1007 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1008 This function is similar to @code{wcpcpy} but copies always exactly
1009 @var{wsize} wide characters into @var{wto}.
1011 If the length of @var{wfrom} is more than @var{size}, then
1012 @code{wcpncpy} copies just the first @var{size} wide characters and
1013 returns a pointer to the wide character directly following the last
1014 non-null wide character which was copied last.  Note that in this case
1015 there is no null terminator written into @var{wto}.
1017 If the length of @var{wfrom} is less than @var{size}, then @code{wcpncpy}
1018 copies all of @var{wfrom}, followed by enough null wide characters to add up
1019 to @var{size} wide characters in all.  This behavior is rarely useful, but it
1020 is implemented to be useful in contexts where this behavior of the
1021 @code{wcsncpy} is used.  @code{wcpncpy} returns a pointer to the
1022 @emph{first} written null wide character.
1024 This function is not part of ISO or POSIX but was found useful while
1025 developing @theglibc{} itself.
1027 Its behavior is undefined if the strings overlap.
1029 As noted below, this function is generally a poor choice for
1030 processing text.
1032 @code{wcpncpy} is a GNU extension.
1033 @end deftypefun
1035 @comment string.h
1036 @comment ISO
1037 @deftypefun {char *} strncat (char *restrict @var{to}, const char *restrict @var{from}, size_t @var{size})
1038 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1039 This function is like @code{strcat} except that not more than @var{size}
1040 bytes from @var{from} are appended to the end of @var{to}, and
1041 @var{from} need not be null-terminated.  A single null byte is also
1042 always appended to @var{to}, so the total
1043 allocated size of @var{to} must be at least @code{@var{size} + 1} bytes
1044 longer than its initial length.
1046 The @code{strncat} function could be implemented like this:
1048 @smallexample
1049 @group
1050 char *
1051 strncat (char *to, const char *from, size_t size)
1053   size_t len = strlen (to);
1054   memcpy (to + len, from, strnlen (from, size));
1055   to[len + strnlen (from, size)] = '\0';
1056   return to;
1058 @end group
1059 @end smallexample
1061 The behavior of @code{strncat} is undefined if the strings overlap.
1063 As a companion to @code{strncpy}, @code{strncat} was designed for
1064 now-rarely-used arrays consisting of non-null bytes followed by zero
1065 or more null bytes.  As noted below, this function is generally a poor
1066 choice for processing text.  Also, this function has significant
1067 performance issues.  @xref{Concatenating Strings}.
1068 @end deftypefun
1070 @comment wchar.h
1071 @comment ISO
1072 @deftypefun {wchar_t *} wcsncat (wchar_t *restrict @var{wto}, const wchar_t *restrict @var{wfrom}, size_t @var{size})
1073 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1074 This function is like @code{wcscat} except that not more than @var{size}
1075 wide characters from @var{from} are appended to the end of @var{to},
1076 and @var{from} need not be null-terminated.  A single null wide
1077 character is also always appended to @var{to}, so the total allocated
1078 size of @var{to} must be at least @code{wcsnlen (@var{wfrom},
1079 @var{size}) + 1} wide characters longer than its initial length.
1081 The @code{wcsncat} function could be implemented like this:
1083 @smallexample
1084 @group
1085 wchar_t *
1086 wcsncat (wchar_t *restrict wto, const wchar_t *restrict wfrom,
1087          size_t size)
1089   size_t len = wcslen (wto);
1090   memcpy (wto + len, wfrom, wcsnlen (wfrom, size) * sizeof (wchar_t));
1091   wto[len + wcsnlen (wfrom, size)] = L'\0';
1092   return wto;
1094 @end group
1095 @end smallexample
1097 The behavior of @code{wcsncat} is undefined if the strings overlap.
1099 As noted below, this function is generally a poor choice for
1100 processing text.  Also, this function has significant performance
1101 issues.  @xref{Concatenating Strings}.
1102 @end deftypefun
1104 Because these functions can abruptly truncate strings or wide strings,
1105 they are generally poor choices for processing text.  When coping or
1106 concatening multibyte strings, they can truncate within a multibyte
1107 character so that the result is not a valid multibyte string.  When
1108 combining or concatenating multibyte or wide strings, they may
1109 truncate the output after a combining character, resulting in a
1110 corrupted grapheme.  They can cause bugs even when processing
1111 single-byte strings: for example, when calculating an ASCII-only user
1112 name, a truncated name can identify the wrong user.
1114 Although some buffer overruns can be prevented by manually replacing
1115 calls to copying functions with calls to truncation functions, there
1116 are often easier and safer automatic techniques that cause buffer
1117 overruns to reliably terminate a program, such as GCC's
1118 @option{-fcheck-pointer-bounds} and @option{-fsanitize=address}
1119 options.  @xref{Debugging Options,, Options for Debugging Your Program
1120 or GCC, gcc.info, Using GCC}.  Because truncation functions can mask
1121 application bugs that would otherwise be caught by the automatic
1122 techniques, these functions should be used only when the application's
1123 underlying logic requires truncation.
1125 @strong{Note:} GNU programs should not truncate strings or wide
1126 strings to fit arbitrary size limits.  @xref{Semantics, , Writing
1127 Robust Programs, standards, The GNU Coding Standards}.  Instead of
1128 string-truncation functions, it is usually better to use dynamic
1129 memory allocation (@pxref{Unconstrained Allocation}) and functions
1130 such as @code{strdup} or @code{asprintf} to construct strings.
1132 @node String/Array Comparison
1133 @section String/Array Comparison
1134 @cindex comparing strings and arrays
1135 @cindex string comparison functions
1136 @cindex array comparison functions
1137 @cindex predicates on strings
1138 @cindex predicates on arrays
1140 You can use the functions in this section to perform comparisons on the
1141 contents of strings and arrays.  As well as checking for equality, these
1142 functions can also be used as the ordering functions for sorting
1143 operations.  @xref{Searching and Sorting}, for an example of this.
1145 Unlike most comparison operations in C, the string comparison functions
1146 return a nonzero value if the strings are @emph{not} equivalent rather
1147 than if they are.  The sign of the value indicates the relative ordering
1148 of the first part of the strings that are not equivalent:  a
1149 negative value indicates that the first string is ``less'' than the
1150 second, while a positive value indicates that the first string is
1151 ``greater''.
1153 The most common use of these functions is to check only for equality.
1154 This is canonically done with an expression like @w{@samp{! strcmp (s1, s2)}}.
1156 All of these functions are declared in the header file @file{string.h}.
1157 @pindex string.h
1159 @comment string.h
1160 @comment ISO
1161 @deftypefun int memcmp (const void *@var{a1}, const void *@var{a2}, size_t @var{size})
1162 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1163 The function @code{memcmp} compares the @var{size} bytes of memory
1164 beginning at @var{a1} against the @var{size} bytes of memory beginning
1165 at @var{a2}.  The value returned has the same sign as the difference
1166 between the first differing pair of bytes (interpreted as @code{unsigned
1167 char} objects, then promoted to @code{int}).
1169 If the contents of the two blocks are equal, @code{memcmp} returns
1170 @code{0}.
1171 @end deftypefun
1173 @comment wchar.h
1174 @comment ISO
1175 @deftypefun int wmemcmp (const wchar_t *@var{a1}, const wchar_t *@var{a2}, size_t @var{size})
1176 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1177 The function @code{wmemcmp} compares the @var{size} wide characters
1178 beginning at @var{a1} against the @var{size} wide characters beginning
1179 at @var{a2}.  The value returned is smaller than or larger than zero
1180 depending on whether the first differing wide character is @var{a1} is
1181 smaller or larger than the corresponding wide character in @var{a2}.
1183 If the contents of the two blocks are equal, @code{wmemcmp} returns
1184 @code{0}.
1185 @end deftypefun
1187 On arbitrary arrays, the @code{memcmp} function is mostly useful for
1188 testing equality.  It usually isn't meaningful to do byte-wise ordering
1189 comparisons on arrays of things other than bytes.  For example, a
1190 byte-wise comparison on the bytes that make up floating-point numbers
1191 isn't likely to tell you anything about the relationship between the
1192 values of the floating-point numbers.
1194 @code{wmemcmp} is really only useful to compare arrays of type
1195 @code{wchar_t} since the function looks at @code{sizeof (wchar_t)} bytes
1196 at a time and this number of bytes is system dependent.
1198 You should also be careful about using @code{memcmp} to compare objects
1199 that can contain ``holes'', such as the padding inserted into structure
1200 objects to enforce alignment requirements, extra space at the end of
1201 unions, and extra bytes at the ends of strings whose length is less
1202 than their allocated size.  The contents of these ``holes'' are
1203 indeterminate and may cause strange behavior when performing byte-wise
1204 comparisons.  For more predictable results, perform an explicit
1205 component-wise comparison.
1207 For example, given a structure type definition like:
1209 @smallexample
1210 struct foo
1211   @{
1212     unsigned char tag;
1213     union
1214       @{
1215         double f;
1216         long i;
1217         char *p;
1218       @} value;
1219   @};
1220 @end smallexample
1222 @noindent
1223 you are better off writing a specialized comparison function to compare
1224 @code{struct foo} objects instead of comparing them with @code{memcmp}.
1226 @comment string.h
1227 @comment ISO
1228 @deftypefun int strcmp (const char *@var{s1}, const char *@var{s2})
1229 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1230 The @code{strcmp} function compares the string @var{s1} against
1231 @var{s2}, returning a value that has the same sign as the difference
1232 between the first differing pair of bytes (interpreted as
1233 @code{unsigned char} objects, then promoted to @code{int}).
1235 If the two strings are equal, @code{strcmp} returns @code{0}.
1237 A consequence of the ordering used by @code{strcmp} is that if @var{s1}
1238 is an initial substring of @var{s2}, then @var{s1} is considered to be
1239 ``less than'' @var{s2}.
1241 @code{strcmp} does not take sorting conventions of the language the
1242 strings are written in into account.  To get that one has to use
1243 @code{strcoll}.
1244 @end deftypefun
1246 @comment wchar.h
1247 @comment ISO
1248 @deftypefun int wcscmp (const wchar_t *@var{ws1}, const wchar_t *@var{ws2})
1249 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1251 The @code{wcscmp} function compares the wide string @var{ws1}
1252 against @var{ws2}.  The value returned is smaller than or larger than zero
1253 depending on whether the first differing wide character is @var{ws1} is
1254 smaller or larger than the corresponding wide character in @var{ws2}.
1256 If the two strings are equal, @code{wcscmp} returns @code{0}.
1258 A consequence of the ordering used by @code{wcscmp} is that if @var{ws1}
1259 is an initial substring of @var{ws2}, then @var{ws1} is considered to be
1260 ``less than'' @var{ws2}.
1262 @code{wcscmp} does not take sorting conventions of the language the
1263 strings are written in into account.  To get that one has to use
1264 @code{wcscoll}.
1265 @end deftypefun
1267 @comment string.h
1268 @comment BSD
1269 @deftypefun int strcasecmp (const char *@var{s1}, const char *@var{s2})
1270 @safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
1271 @c Although this calls tolower multiple times, it's a macro, and
1272 @c strcasecmp is optimized so that the locale pointer is read only once.
1273 @c There are some asm implementations too, for which the single-read
1274 @c from locale TLS pointers also applies.
1275 This function is like @code{strcmp}, except that differences in case are
1276 ignored, and its arguments must be multibyte strings.
1277 How uppercase and lowercase characters are related is
1278 determined by the currently selected locale.  In the standard @code{"C"}
1279 locale the characters @"A and @"a do not match but in a locale which
1280 regards these characters as parts of the alphabet they do match.
1282 @noindent
1283 @code{strcasecmp} is derived from BSD.
1284 @end deftypefun
1286 @comment wchar.h
1287 @comment GNU
1288 @deftypefun int wcscasecmp (const wchar_t *@var{ws1}, const wchar_t *@var{ws2})
1289 @safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
1290 @c Since towlower is not a macro, the locale object may be read multiple
1291 @c times.
1292 This function is like @code{wcscmp}, except that differences in case are
1293 ignored.  How uppercase and lowercase characters are related is
1294 determined by the currently selected locale.  In the standard @code{"C"}
1295 locale the characters @"A and @"a do not match but in a locale which
1296 regards these characters as parts of the alphabet they do match.
1298 @noindent
1299 @code{wcscasecmp} is a GNU extension.
1300 @end deftypefun
1302 @comment string.h
1303 @comment ISO
1304 @deftypefun int strncmp (const char *@var{s1}, const char *@var{s2}, size_t @var{size})
1305 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1306 This function is the similar to @code{strcmp}, except that no more than
1307 @var{size} bytes are compared.  In other words, if the two
1308 strings are the same in their first @var{size} bytes, the
1309 return value is zero.
1310 @end deftypefun
1312 @comment wchar.h
1313 @comment ISO
1314 @deftypefun int wcsncmp (const wchar_t *@var{ws1}, const wchar_t *@var{ws2}, size_t @var{size})
1315 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1316 This function is similar to @code{wcscmp}, except that no more than
1317 @var{size} wide characters are compared.  In other words, if the two
1318 strings are the same in their first @var{size} wide characters, the
1319 return value is zero.
1320 @end deftypefun
1322 @comment string.h
1323 @comment BSD
1324 @deftypefun int strncasecmp (const char *@var{s1}, const char *@var{s2}, size_t @var{n})
1325 @safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
1326 This function is like @code{strncmp}, except that differences in case
1327 are ignored, and the compared parts of the arguments should consist of
1328 valid multibyte characters.
1329 Like @code{strcasecmp}, it is locale dependent how
1330 uppercase and lowercase characters are related.
1332 @noindent
1333 @code{strncasecmp} is a GNU extension.
1334 @end deftypefun
1336 @comment wchar.h
1337 @comment GNU
1338 @deftypefun int wcsncasecmp (const wchar_t *@var{ws1}, const wchar_t *@var{s2}, size_t @var{n})
1339 @safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
1340 This function is like @code{wcsncmp}, except that differences in case
1341 are ignored.  Like @code{wcscasecmp}, it is locale dependent how
1342 uppercase and lowercase characters are related.
1344 @noindent
1345 @code{wcsncasecmp} is a GNU extension.
1346 @end deftypefun
1348 Here are some examples showing the use of @code{strcmp} and
1349 @code{strncmp} (equivalent examples can be constructed for the wide
1350 character functions).  These examples assume the use of the ASCII
1351 character set.  (If some other character set---say, EBCDIC---is used
1352 instead, then the glyphs are associated with different numeric codes,
1353 and the return values and ordering may differ.)
1355 @smallexample
1356 strcmp ("hello", "hello")
1357     @result{} 0    /* @r{These two strings are the same.} */
1358 strcmp ("hello", "Hello")
1359     @result{} 32   /* @r{Comparisons are case-sensitive.} */
1360 strcmp ("hello", "world")
1361     @result{} -15  /* @r{The byte @code{'h'} comes before @code{'w'}.} */
1362 strcmp ("hello", "hello, world")
1363     @result{} -44  /* @r{Comparing a null byte against a comma.} */
1364 strncmp ("hello", "hello, world", 5)
1365     @result{} 0    /* @r{The initial 5 bytes are the same.} */
1366 strncmp ("hello, world", "hello, stupid world!!!", 5)
1367     @result{} 0    /* @r{The initial 5 bytes are the same.} */
1368 @end smallexample
1370 @comment string.h
1371 @comment GNU
1372 @deftypefun int strverscmp (const char *@var{s1}, const char *@var{s2})
1373 @safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
1374 @c Calls isdigit multiple times, locale may change in between.
1375 The @code{strverscmp} function compares the string @var{s1} against
1376 @var{s2}, considering them as holding indices/version numbers.  The
1377 return value follows the same conventions as found in the
1378 @code{strcmp} function.  In fact, if @var{s1} and @var{s2} contain no
1379 digits, @code{strverscmp} behaves like @code{strcmp}
1380 (in the sense that the sign of the result is the same).
1382 The comparison algorithm which the @code{strverscmp} function implements
1383 differs slightly from other version-comparison algorithms.  The
1384 implementation is based on a finite-state machine, whose behavior is
1385 approximated below.
1387 @itemize @bullet
1388 @item
1389 The input strings are each split into sequences of non-digits and
1390 digits.  These sequences can be empty at the beginning and end of the
1391 string.  Digits are determined by the @code{isdigit} function and are
1392 thus subject to the current locale.
1394 @item
1395 Comparison starts with a (possibly empty) non-digit sequence.  The first
1396 non-equal sequences of non-digits or digits determines the outcome of
1397 the comparison.
1399 @item
1400 Corresponding non-digit sequences in both strings are compared
1401 lexicographically if their lengths are equal.  If the lengths differ,
1402 the shorter non-digit sequence is extended with the input string
1403 character immediately following it (which may be the null terminator),
1404 the other sequence is truncated to be of the same (extended) length, and
1405 these two sequences are compared lexicographically.  In the last case,
1406 the sequence comparison determines the result of the function because
1407 the extension character (or some character before it) is necessarily
1408 different from the character at the same offset in the other input
1409 string.
1411 @item
1412 For two sequences of digits, the number of leading zeros is counted (which
1413 can be zero).  If the count differs, the string with more leading zeros
1414 in the digit sequence is considered smaller than the other string.
1416 @item
1417 If the two sequences of digits have no leading zeros, they are compared
1418 as integers, that is, the string with the longer digit sequence is
1419 deemed larger, and if both sequences are of equal length, they are
1420 compared lexicographically.
1422 @item
1423 If both digit sequences start with a zero and have an equal number of
1424 leading zeros, they are compared lexicographically if their lengths are
1425 the same.  If the lengths differ, the shorter sequence is extended with
1426 the following character in its input string, and the other sequence is
1427 truncated to the same length, and both sequences are compared
1428 lexicographically (similar to the non-digit sequence case above).
1429 @end itemize
1431 The treatment of leading zeros and the tie-breaking extension characters
1432 (which in effect propagate across non-digit/digit sequence boundaries)
1433 differs from other version-comparison algorithms.
1435 @smallexample
1436 strverscmp ("no digit", "no digit")
1437     @result{} 0    /* @r{same behavior as strcmp.} */
1438 strverscmp ("item#99", "item#100")
1439     @result{} <0   /* @r{same prefix, but 99 < 100.} */
1440 strverscmp ("alpha1", "alpha001")
1441     @result{} >0   /* @r{different number of leading zeros (0 and 2).} */
1442 strverscmp ("part1_f012", "part1_f01")
1443     @result{} >0   /* @r{lexicographical comparison with leading zeros.} */
1444 strverscmp ("foo.009", "foo.0")
1445     @result{} <0   /* @r{different number of leading zeros (2 and 1).} */
1446 @end smallexample
1448 @code{strverscmp} is a GNU extension.
1449 @end deftypefun
1451 @comment string.h
1452 @comment BSD
1453 @deftypefun int bcmp (const void *@var{a1}, const void *@var{a2}, size_t @var{size})
1454 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1455 This is an obsolete alias for @code{memcmp}, derived from BSD.
1456 @end deftypefun
1458 @node Collation Functions
1459 @section Collation Functions
1461 @cindex collating strings
1462 @cindex string collation functions
1464 In some locales, the conventions for lexicographic ordering differ from
1465 the strict numeric ordering of character codes.  For example, in Spanish
1466 most glyphs with diacritical marks such as accents are not considered
1467 distinct letters for the purposes of collation.  On the other hand, the
1468 two-character sequence @samp{ll} is treated as a single letter that is
1469 collated immediately after @samp{l}.
1471 You can use the functions @code{strcoll} and @code{strxfrm} (declared in
1472 the headers file @file{string.h}) and @code{wcscoll} and @code{wcsxfrm}
1473 (declared in the headers file @file{wchar}) to compare strings using a
1474 collation ordering appropriate for the current locale.  The locale used
1475 by these functions in particular can be specified by setting the locale
1476 for the @code{LC_COLLATE} category; see @ref{Locales}.
1477 @pindex string.h
1478 @pindex wchar.h
1480 In the standard C locale, the collation sequence for @code{strcoll} is
1481 the same as that for @code{strcmp}.  Similarly, @code{wcscoll} and
1482 @code{wcscmp} are the same in this situation.
1484 Effectively, the way these functions work is by applying a mapping to
1485 transform the characters in a multibyte string to a byte
1486 sequence that represents
1487 the string's position in the collating sequence of the current locale.
1488 Comparing two such byte sequences in a simple fashion is equivalent to
1489 comparing the strings with the locale's collating sequence.
1491 The functions @code{strcoll} and @code{wcscoll} perform this translation
1492 implicitly, in order to do one comparison.  By contrast, @code{strxfrm}
1493 and @code{wcsxfrm} perform the mapping explicitly.  If you are making
1494 multiple comparisons using the same string or set of strings, it is
1495 likely to be more efficient to use @code{strxfrm} or @code{wcsxfrm} to
1496 transform all the strings just once, and subsequently compare the
1497 transformed strings with @code{strcmp} or @code{wcscmp}.
1499 @comment string.h
1500 @comment ISO
1501 @deftypefun int strcoll (const char *@var{s1}, const char *@var{s2})
1502 @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
1503 @c Calls strcoll_l with the current locale, which dereferences only the
1504 @c LC_COLLATE data pointer.
1505 The @code{strcoll} function is similar to @code{strcmp} but uses the
1506 collating sequence of the current locale for collation (the
1507 @code{LC_COLLATE} locale).  The arguments are multibyte strings.
1508 @end deftypefun
1510 @comment wchar.h
1511 @comment ISO
1512 @deftypefun int wcscoll (const wchar_t *@var{ws1}, const wchar_t *@var{ws2})
1513 @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
1514 @c Same as strcoll, but calling wcscoll_l.
1515 The @code{wcscoll} function is similar to @code{wcscmp} but uses the
1516 collating sequence of the current locale for collation (the
1517 @code{LC_COLLATE} locale).
1518 @end deftypefun
1520 Here is an example of sorting an array of strings, using @code{strcoll}
1521 to compare them.  The actual sort algorithm is not written here; it
1522 comes from @code{qsort} (@pxref{Array Sort Function}).  The job of the
1523 code shown here is to say how to compare the strings while sorting them.
1524 (Later on in this section, we will show a way to do this more
1525 efficiently using @code{strxfrm}.)
1527 @smallexample
1528 /* @r{This is the comparison function used with @code{qsort}.} */
1531 compare_elements (const void *v1, const void *v2)
1533   char * const *p1 = v1;
1534   char * const *p2 = v2;
1536   return strcoll (*p1, *p2);
1539 /* @r{This is the entry point---the function to sort}
1540    @r{strings using the locale's collating sequence.} */
1542 void
1543 sort_strings (char **array, int nstrings)
1545   /* @r{Sort @code{temp_array} by comparing the strings.} */
1546   qsort (array, nstrings,
1547          sizeof (char *), compare_elements);
1549 @end smallexample
1551 @cindex converting string to collation order
1552 @comment string.h
1553 @comment ISO
1554 @deftypefun size_t strxfrm (char *restrict @var{to}, const char *restrict @var{from}, size_t @var{size})
1555 @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
1556 The function @code{strxfrm} transforms the multibyte string
1557 @var{from} using the
1558 collation transformation determined by the locale currently selected for
1559 collation, and stores the transformed string in the array @var{to}.  Up
1560 to @var{size} bytes (including a terminating null byte) are
1561 stored.
1563 The behavior is undefined if the strings @var{to} and @var{from}
1564 overlap; see @ref{Copying Strings and Arrays}.
1566 The return value is the length of the entire transformed string.  This
1567 value is not affected by the value of @var{size}, but if it is greater
1568 or equal than @var{size}, it means that the transformed string did not
1569 entirely fit in the array @var{to}.  In this case, only as much of the
1570 string as actually fits was stored.  To get the whole transformed
1571 string, call @code{strxfrm} again with a bigger output array.
1573 The transformed string may be longer than the original string, and it
1574 may also be shorter.
1576 If @var{size} is zero, no bytes are stored in @var{to}.  In this
1577 case, @code{strxfrm} simply returns the number of bytes that would
1578 be the length of the transformed string.  This is useful for determining
1579 what size the allocated array should be.  It does not matter what
1580 @var{to} is if @var{size} is zero; @var{to} may even be a null pointer.
1581 @end deftypefun
1583 @comment wchar.h
1584 @comment ISO
1585 @deftypefun size_t wcsxfrm (wchar_t *restrict @var{wto}, const wchar_t *@var{wfrom}, size_t @var{size})
1586 @safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
1587 The function @code{wcsxfrm} transforms wide string @var{wfrom}
1588 using the collation transformation determined by the locale currently
1589 selected for collation, and stores the transformed string in the array
1590 @var{wto}.  Up to @var{size} wide characters (including a terminating null
1591 wide character) are stored.
1593 The behavior is undefined if the strings @var{wto} and @var{wfrom}
1594 overlap; see @ref{Copying Strings and Arrays}.
1596 The return value is the length of the entire transformed wide
1597 string.  This value is not affected by the value of @var{size}, but if
1598 it is greater or equal than @var{size}, it means that the transformed
1599 wide string did not entirely fit in the array @var{wto}.  In
1600 this case, only as much of the wide string as actually fits
1601 was stored.  To get the whole transformed wide string, call
1602 @code{wcsxfrm} again with a bigger output array.
1604 The transformed wide string may be longer than the original
1605 wide string, and it may also be shorter.
1607 If @var{size} is zero, no wide characters are stored in @var{to}.  In this
1608 case, @code{wcsxfrm} simply returns the number of wide characters that
1609 would be the length of the transformed wide string.  This is
1610 useful for determining what size the allocated array should be (remember
1611 to multiply with @code{sizeof (wchar_t)}).  It does not matter what
1612 @var{wto} is if @var{size} is zero; @var{wto} may even be a null pointer.
1613 @end deftypefun
1615 Here is an example of how you can use @code{strxfrm} when
1616 you plan to do many comparisons.  It does the same thing as the previous
1617 example, but much faster, because it has to transform each string only
1618 once, no matter how many times it is compared with other strings.  Even
1619 the time needed to allocate and free storage is much less than the time
1620 we save, when there are many strings.
1622 @smallexample
1623 struct sorter @{ char *input; char *transformed; @};
1625 /* @r{This is the comparison function used with @code{qsort}}
1626    @r{to sort an array of @code{struct sorter}.} */
1629 compare_elements (const void *v1, const void *v2)
1631   const struct sorter *p1 = v1;
1632   const struct sorter *p2 = v2;
1634   return strcmp (p1->transformed, p2->transformed);
1637 /* @r{This is the entry point---the function to sort}
1638    @r{strings using the locale's collating sequence.} */
1640 void
1641 sort_strings_fast (char **array, int nstrings)
1643   struct sorter temp_array[nstrings];
1644   int i;
1646   /* @r{Set up @code{temp_array}.  Each element contains}
1647      @r{one input string and its transformed string.} */
1648   for (i = 0; i < nstrings; i++)
1649     @{
1650       size_t length = strlen (array[i]) * 2;
1651       char *transformed;
1652       size_t transformed_length;
1654       temp_array[i].input = array[i];
1656       /* @r{First try a buffer perhaps big enough.}  */
1657       transformed = (char *) xmalloc (length);
1659       /* @r{Transform @code{array[i]}.}  */
1660       transformed_length = strxfrm (transformed, array[i], length);
1662       /* @r{If the buffer was not large enough, resize it}
1663          @r{and try again.}  */
1664       if (transformed_length >= length)
1665         @{
1666           /* @r{Allocate the needed space. +1 for terminating}
1667              @r{@code{'\0'} byte.}  */
1668           transformed = (char *) xrealloc (transformed,
1669                                            transformed_length + 1);
1671           /* @r{The return value is not interesting because we know}
1672              @r{how long the transformed string is.}  */
1673           (void) strxfrm (transformed, array[i],
1674                           transformed_length + 1);
1675         @}
1677       temp_array[i].transformed = transformed;
1678     @}
1680   /* @r{Sort @code{temp_array} by comparing transformed strings.} */
1681   qsort (temp_array, nstrings,
1682          sizeof (struct sorter), compare_elements);
1684   /* @r{Put the elements back in the permanent array}
1685      @r{in their sorted order.} */
1686   for (i = 0; i < nstrings; i++)
1687     array[i] = temp_array[i].input;
1689   /* @r{Free the strings we allocated.} */
1690   for (i = 0; i < nstrings; i++)
1691     free (temp_array[i].transformed);
1693 @end smallexample
1695 The interesting part of this code for the wide character version would
1696 look like this:
1698 @smallexample
1699 void
1700 sort_strings_fast (wchar_t **array, int nstrings)
1702   @dots{}
1703       /* @r{Transform @code{array[i]}.}  */
1704       transformed_length = wcsxfrm (transformed, array[i], length);
1706       /* @r{If the buffer was not large enough, resize it}
1707          @r{and try again.}  */
1708       if (transformed_length >= length)
1709         @{
1710           /* @r{Allocate the needed space. +1 for terminating}
1711              @r{@code{L'\0'} wide character.}  */
1712           transformed = (wchar_t *) xrealloc (transformed,
1713                                               (transformed_length + 1)
1714                                               * sizeof (wchar_t));
1716           /* @r{The return value is not interesting because we know}
1717              @r{how long the transformed string is.}  */
1718           (void) wcsxfrm (transformed, array[i],
1719                           transformed_length + 1);
1720         @}
1721   @dots{}
1722 @end smallexample
1724 @noindent
1725 Note the additional multiplication with @code{sizeof (wchar_t)} in the
1726 @code{realloc} call.
1728 @strong{Compatibility Note:} The string collation functions are a new
1729 feature of @w{ISO C90}.  Older C dialects have no equivalent feature.
1730 The wide character versions were introduced in @w{Amendment 1} to @w{ISO
1731 C90}.
1733 @node Search Functions
1734 @section Search Functions
1736 This section describes library functions which perform various kinds
1737 of searching operations on strings and arrays.  These functions are
1738 declared in the header file @file{string.h}.
1739 @pindex string.h
1740 @cindex search functions (for strings)
1741 @cindex string search functions
1743 @comment string.h
1744 @comment ISO
1745 @deftypefun {void *} memchr (const void *@var{block}, int @var{c}, size_t @var{size})
1746 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1747 This function finds the first occurrence of the byte @var{c} (converted
1748 to an @code{unsigned char}) in the initial @var{size} bytes of the
1749 object beginning at @var{block}.  The return value is a pointer to the
1750 located byte, or a null pointer if no match was found.
1751 @end deftypefun
1753 @comment wchar.h
1754 @comment ISO
1755 @deftypefun {wchar_t *} wmemchr (const wchar_t *@var{block}, wchar_t @var{wc}, size_t @var{size})
1756 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1757 This function finds the first occurrence of the wide character @var{wc}
1758 in the initial @var{size} wide characters of the object beginning at
1759 @var{block}.  The return value is a pointer to the located wide
1760 character, or a null pointer if no match was found.
1761 @end deftypefun
1763 @comment string.h
1764 @comment GNU
1765 @deftypefun {void *} rawmemchr (const void *@var{block}, int @var{c})
1766 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1767 Often the @code{memchr} function is used with the knowledge that the
1768 byte @var{c} is available in the memory block specified by the
1769 parameters.  But this means that the @var{size} parameter is not really
1770 needed and that the tests performed with it at runtime (to check whether
1771 the end of the block is reached) are not needed.
1773 The @code{rawmemchr} function exists for just this situation which is
1774 surprisingly frequent.  The interface is similar to @code{memchr} except
1775 that the @var{size} parameter is missing.  The function will look beyond
1776 the end of the block pointed to by @var{block} in case the programmer
1777 made an error in assuming that the byte @var{c} is present in the block.
1778 In this case the result is unspecified.  Otherwise the return value is a
1779 pointer to the located byte.
1781 This function is of special interest when looking for the end of a
1782 string.  Since all strings are terminated by a null byte a call like
1784 @smallexample
1785    rawmemchr (str, '\0')
1786 @end smallexample
1788 @noindent
1789 will never go beyond the end of the string.
1791 This function is a GNU extension.
1792 @end deftypefun
1794 @comment string.h
1795 @comment GNU
1796 @deftypefun {void *} memrchr (const void *@var{block}, int @var{c}, size_t @var{size})
1797 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1798 The function @code{memrchr} is like @code{memchr}, except that it searches
1799 backwards from the end of the block defined by @var{block} and @var{size}
1800 (instead of forwards from the front).
1802 This function is a GNU extension.
1803 @end deftypefun
1805 @comment string.h
1806 @comment ISO
1807 @deftypefun {char *} strchr (const char *@var{string}, int @var{c})
1808 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1809 The @code{strchr} function finds the first occurrence of the byte
1810 @var{c} (converted to a @code{char}) in the string
1811 beginning at @var{string}.  The return value is a pointer to the located
1812 byte, or a null pointer if no match was found.
1814 For example,
1815 @smallexample
1816 strchr ("hello, world", 'l')
1817     @result{} "llo, world"
1818 strchr ("hello, world", '?')
1819     @result{} NULL
1820 @end smallexample
1822 The terminating null byte is considered to be part of the string,
1823 so you can use this function get a pointer to the end of a string by
1824 specifying zero as the value of the @var{c} argument.
1826 When @code{strchr} returns a null pointer, it does not let you know
1827 the position of the terminating null byte it has found.  If you
1828 need that information, it is better (but less portable) to use
1829 @code{strchrnul} than to search for it a second time.
1830 @end deftypefun
1832 @comment wchar.h
1833 @comment ISO
1834 @deftypefun {wchar_t *} wcschr (const wchar_t *@var{wstring}, int @var{wc})
1835 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1836 The @code{wcschr} function finds the first occurrence of the wide
1837 character @var{wc} in the wide string
1838 beginning at @var{wstring}.  The return value is a pointer to the
1839 located wide character, or a null pointer if no match was found.
1841 The terminating null wide character is considered to be part of the wide
1842 string, so you can use this function get a pointer to the end
1843 of a wide string by specifying a null wide character as the
1844 value of the @var{wc} argument.  It would be better (but less portable)
1845 to use @code{wcschrnul} in this case, though.
1846 @end deftypefun
1848 @comment string.h
1849 @comment GNU
1850 @deftypefun {char *} strchrnul (const char *@var{string}, int @var{c})
1851 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1852 @code{strchrnul} is the same as @code{strchr} except that if it does
1853 not find the byte, it returns a pointer to string's terminating
1854 null byte rather than a null pointer.
1856 This function is a GNU extension.
1857 @end deftypefun
1859 @comment wchar.h
1860 @comment GNU
1861 @deftypefun {wchar_t *} wcschrnul (const wchar_t *@var{wstring}, wchar_t @var{wc})
1862 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1863 @code{wcschrnul} is the same as @code{wcschr} except that if it does not
1864 find the wide character, it returns a pointer to the wide string's
1865 terminating null wide character rather than a null pointer.
1867 This function is a GNU extension.
1868 @end deftypefun
1870 One useful, but unusual, use of the @code{strchr}
1871 function is when one wants to have a pointer pointing to the null byte
1872 terminating a string.  This is often written in this way:
1874 @smallexample
1875   s += strlen (s);
1876 @end smallexample
1878 @noindent
1879 This is almost optimal but the addition operation duplicated a bit of
1880 the work already done in the @code{strlen} function.  A better solution
1881 is this:
1883 @smallexample
1884   s = strchr (s, '\0');
1885 @end smallexample
1887 There is no restriction on the second parameter of @code{strchr} so it
1888 could very well also be zero.  Those readers thinking very
1889 hard about this might now point out that the @code{strchr} function is
1890 more expensive than the @code{strlen} function since we have two abort
1891 criteria.  This is right.  But in @theglibc{} the implementation of
1892 @code{strchr} is optimized in a special way so that @code{strchr}
1893 actually is faster.
1895 @comment string.h
1896 @comment ISO
1897 @deftypefun {char *} strrchr (const char *@var{string}, int @var{c})
1898 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1899 The function @code{strrchr} is like @code{strchr}, except that it searches
1900 backwards from the end of the string @var{string} (instead of forwards
1901 from the front).
1903 For example,
1904 @smallexample
1905 strrchr ("hello, world", 'l')
1906     @result{} "ld"
1907 @end smallexample
1908 @end deftypefun
1910 @comment wchar.h
1911 @comment ISO
1912 @deftypefun {wchar_t *} wcsrchr (const wchar_t *@var{wstring}, wchar_t @var{c})
1913 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1914 The function @code{wcsrchr} is like @code{wcschr}, except that it searches
1915 backwards from the end of the string @var{wstring} (instead of forwards
1916 from the front).
1917 @end deftypefun
1919 @comment string.h
1920 @comment ISO
1921 @deftypefun {char *} strstr (const char *@var{haystack}, const char *@var{needle})
1922 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1923 This is like @code{strchr}, except that it searches @var{haystack} for a
1924 substring @var{needle} rather than just a single byte.  It
1925 returns a pointer into the string @var{haystack} that is the first
1926 byte of the substring, or a null pointer if no match was found.  If
1927 @var{needle} is an empty string, the function returns @var{haystack}.
1929 For example,
1930 @smallexample
1931 strstr ("hello, world", "l")
1932     @result{} "llo, world"
1933 strstr ("hello, world", "wo")
1934     @result{} "world"
1935 @end smallexample
1936 @end deftypefun
1938 @comment wchar.h
1939 @comment ISO
1940 @deftypefun {wchar_t *} wcsstr (const wchar_t *@var{haystack}, const wchar_t *@var{needle})
1941 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1942 This is like @code{wcschr}, except that it searches @var{haystack} for a
1943 substring @var{needle} rather than just a single wide character.  It
1944 returns a pointer into the string @var{haystack} that is the first wide
1945 character of the substring, or a null pointer if no match was found.  If
1946 @var{needle} is an empty string, the function returns @var{haystack}.
1947 @end deftypefun
1949 @comment wchar.h
1950 @comment XPG
1951 @deftypefun {wchar_t *} wcswcs (const wchar_t *@var{haystack}, const wchar_t *@var{needle})
1952 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1953 @code{wcswcs} is a deprecated alias for @code{wcsstr}.  This is the
1954 name originally used in the X/Open Portability Guide before the
1955 @w{Amendment 1} to @w{ISO C90} was published.
1956 @end deftypefun
1959 @comment string.h
1960 @comment GNU
1961 @deftypefun {char *} strcasestr (const char *@var{haystack}, const char *@var{needle})
1962 @safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
1963 @c There may be multiple calls of strncasecmp, each accessing the locale
1964 @c object independently.
1965 This is like @code{strstr}, except that it ignores case in searching for
1966 the substring.   Like @code{strcasecmp}, it is locale dependent how
1967 uppercase and lowercase characters are related, and arguments are
1968 multibyte strings.
1971 For example,
1972 @smallexample
1973 strcasestr ("hello, world", "L")
1974     @result{} "llo, world"
1975 strcasestr ("hello, World", "wo")
1976     @result{} "World"
1977 @end smallexample
1978 @end deftypefun
1981 @comment string.h
1982 @comment GNU
1983 @deftypefun {void *} memmem (const void *@var{haystack}, size_t @var{haystack-len},@*const void *@var{needle}, size_t @var{needle-len})
1984 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1985 This is like @code{strstr}, but @var{needle} and @var{haystack} are byte
1986 arrays rather than strings.  @var{needle-len} is the
1987 length of @var{needle} and @var{haystack-len} is the length of
1988 @var{haystack}.@refill
1990 This function is a GNU extension.
1991 @end deftypefun
1993 @comment string.h
1994 @comment ISO
1995 @deftypefun size_t strspn (const char *@var{string}, const char *@var{skipset})
1996 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1997 The @code{strspn} (``string span'') function returns the length of the
1998 initial substring of @var{string} that consists entirely of bytes that
1999 are members of the set specified by the string @var{skipset}.  The order
2000 of the bytes in @var{skipset} is not important.
2002 For example,
2003 @smallexample
2004 strspn ("hello, world", "abcdefghijklmnopqrstuvwxyz")
2005     @result{} 5
2006 @end smallexample
2008 In a multibyte string, characters consisting of
2009 more than one byte are not treated as single entities.  Each byte is treated
2010 separately.  The function is not locale-dependent.
2011 @end deftypefun
2013 @comment wchar.h
2014 @comment ISO
2015 @deftypefun size_t wcsspn (const wchar_t *@var{wstring}, const wchar_t *@var{skipset})
2016 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2017 The @code{wcsspn} (``wide character string span'') function returns the
2018 length of the initial substring of @var{wstring} that consists entirely
2019 of wide characters that are members of the set specified by the string
2020 @var{skipset}.  The order of the wide characters in @var{skipset} is not
2021 important.
2022 @end deftypefun
2024 @comment string.h
2025 @comment ISO
2026 @deftypefun size_t strcspn (const char *@var{string}, const char *@var{stopset})
2027 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2028 The @code{strcspn} (``string complement span'') function returns the length
2029 of the initial substring of @var{string} that consists entirely of bytes
2030 that are @emph{not} members of the set specified by the string @var{stopset}.
2031 (In other words, it returns the offset of the first byte in @var{string}
2032 that is a member of the set @var{stopset}.)
2034 For example,
2035 @smallexample
2036 strcspn ("hello, world", " \t\n,.;!?")
2037     @result{} 5
2038 @end smallexample
2040 In a multibyte string, characters consisting of
2041 more than one byte are not treated as a single entities.  Each byte is treated
2042 separately.  The function is not locale-dependent.
2043 @end deftypefun
2045 @comment wchar.h
2046 @comment ISO
2047 @deftypefun size_t wcscspn (const wchar_t *@var{wstring}, const wchar_t *@var{stopset})
2048 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2049 The @code{wcscspn} (``wide character string complement span'') function
2050 returns the length of the initial substring of @var{wstring} that
2051 consists entirely of wide characters that are @emph{not} members of the
2052 set specified by the string @var{stopset}.  (In other words, it returns
2053 the offset of the first wide character in @var{string} that is a member of
2054 the set @var{stopset}.)
2055 @end deftypefun
2057 @comment string.h
2058 @comment ISO
2059 @deftypefun {char *} strpbrk (const char *@var{string}, const char *@var{stopset})
2060 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2061 The @code{strpbrk} (``string pointer break'') function is related to
2062 @code{strcspn}, except that it returns a pointer to the first byte
2063 in @var{string} that is a member of the set @var{stopset} instead of the
2064 length of the initial substring.  It returns a null pointer if no such
2065 byte from @var{stopset} is found.
2067 @c @group  Invalid outside the example.
2068 For example,
2070 @smallexample
2071 strpbrk ("hello, world", " \t\n,.;!?")
2072     @result{} ", world"
2073 @end smallexample
2074 @c @end group
2076 In a multibyte string, characters consisting of
2077 more than one byte are not treated as single entities.  Each byte is treated
2078 separately.  The function is not locale-dependent.
2079 @end deftypefun
2081 @comment wchar.h
2082 @comment ISO
2083 @deftypefun {wchar_t *} wcspbrk (const wchar_t *@var{wstring}, const wchar_t *@var{stopset})
2084 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2085 The @code{wcspbrk} (``wide character string pointer break'') function is
2086 related to @code{wcscspn}, except that it returns a pointer to the first
2087 wide character in @var{wstring} that is a member of the set
2088 @var{stopset} instead of the length of the initial substring.  It
2089 returns a null pointer if no such wide character from @var{stopset} is found.
2090 @end deftypefun
2093 @subsection Compatibility String Search Functions
2095 @comment string.h
2096 @comment BSD
2097 @deftypefun {char *} index (const char *@var{string}, int @var{c})
2098 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2099 @code{index} is another name for @code{strchr}; they are exactly the same.
2100 New code should always use @code{strchr} since this name is defined in
2101 @w{ISO C} while @code{index} is a BSD invention which never was available
2102 on @w{System V} derived systems.
2103 @end deftypefun
2105 @comment string.h
2106 @comment BSD
2107 @deftypefun {char *} rindex (const char *@var{string}, int @var{c})
2108 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2109 @code{rindex} is another name for @code{strrchr}; they are exactly the same.
2110 New code should always use @code{strrchr} since this name is defined in
2111 @w{ISO C} while @code{rindex} is a BSD invention which never was available
2112 on @w{System V} derived systems.
2113 @end deftypefun
2115 @node Finding Tokens in a String
2116 @section Finding Tokens in a String
2118 @cindex tokenizing strings
2119 @cindex breaking a string into tokens
2120 @cindex parsing tokens from a string
2121 It's fairly common for programs to have a need to do some simple kinds
2122 of lexical analysis and parsing, such as splitting a command string up
2123 into tokens.  You can do this with the @code{strtok} function, declared
2124 in the header file @file{string.h}.
2125 @pindex string.h
2127 @comment string.h
2128 @comment ISO
2129 @deftypefun {char *} strtok (char *restrict @var{newstring}, const char *restrict @var{delimiters})
2130 @safety{@prelim{}@mtunsafe{@mtasurace{:strtok}}@asunsafe{}@acsafe{}}
2131 A string can be split into tokens by making a series of calls to the
2132 function @code{strtok}.
2134 The string to be split up is passed as the @var{newstring} argument on
2135 the first call only.  The @code{strtok} function uses this to set up
2136 some internal state information.  Subsequent calls to get additional
2137 tokens from the same string are indicated by passing a null pointer as
2138 the @var{newstring} argument.  Calling @code{strtok} with another
2139 non-null @var{newstring} argument reinitializes the state information.
2140 It is guaranteed that no other library function ever calls @code{strtok}
2141 behind your back (which would mess up this internal state information).
2143 The @var{delimiters} argument is a string that specifies a set of delimiters
2144 that may surround the token being extracted.  All the initial bytes
2145 that are members of this set are discarded.  The first byte that is
2146 @emph{not} a member of this set of delimiters marks the beginning of the
2147 next token.  The end of the token is found by looking for the next
2148 byte that is a member of the delimiter set.  This byte in the
2149 original string @var{newstring} is overwritten by a null byte, and the
2150 pointer to the beginning of the token in @var{newstring} is returned.
2152 On the next call to @code{strtok}, the searching begins at the next
2153 byte beyond the one that marked the end of the previous token.
2154 Note that the set of delimiters @var{delimiters} do not have to be the
2155 same on every call in a series of calls to @code{strtok}.
2157 If the end of the string @var{newstring} is reached, or if the remainder of
2158 string consists only of delimiter bytes, @code{strtok} returns
2159 a null pointer.
2161 In a multibyte string, characters consisting of
2162 more than one byte are not treated as single entities.  Each byte is treated
2163 separately.  The function is not locale-dependent.
2164 @end deftypefun
2166 @comment wchar.h
2167 @comment ISO
2168 @deftypefun {wchar_t *} wcstok (wchar_t *@var{newstring}, const wchar_t *@var{delimiters}, wchar_t **@var{save_ptr})
2169 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2170 A string can be split into tokens by making a series of calls to the
2171 function @code{wcstok}.
2173 The string to be split up is passed as the @var{newstring} argument on
2174 the first call only.  The @code{wcstok} function uses this to set up
2175 some internal state information.  Subsequent calls to get additional
2176 tokens from the same wide string are indicated by passing a
2177 null pointer as the @var{newstring} argument, which causes the pointer
2178 previously stored in @var{save_ptr} to be used instead.
2180 The @var{delimiters} argument is a wide string that specifies
2181 a set of delimiters that may surround the token being extracted.  All
2182 the initial wide characters that are members of this set are discarded.
2183 The first wide character that is @emph{not} a member of this set of
2184 delimiters marks the beginning of the next token.  The end of the token
2185 is found by looking for the next wide character that is a member of the
2186 delimiter set.  This wide character in the original wide
2187 string @var{newstring} is overwritten by a null wide character, the
2188 pointer past the overwritten wide character is saved in @var{save_ptr},
2189 and the pointer to the beginning of the token in @var{newstring} is
2190 returned.
2192 On the next call to @code{wcstok}, the searching begins at the next
2193 wide character beyond the one that marked the end of the previous token.
2194 Note that the set of delimiters @var{delimiters} do not have to be the
2195 same on every call in a series of calls to @code{wcstok}.
2197 If the end of the wide string @var{newstring} is reached, or
2198 if the remainder of string consists only of delimiter wide characters,
2199 @code{wcstok} returns a null pointer.
2200 @end deftypefun
2202 @strong{Warning:} Since @code{strtok} and @code{wcstok} alter the string
2203 they is parsing, you should always copy the string to a temporary buffer
2204 before parsing it with @code{strtok}/@code{wcstok} (@pxref{Copying Strings
2205 and Arrays}).  If you allow @code{strtok} or @code{wcstok} to modify
2206 a string that came from another part of your program, you are asking for
2207 trouble; that string might be used for other purposes after
2208 @code{strtok} or @code{wcstok} has modified it, and it would not have
2209 the expected value.
2211 The string that you are operating on might even be a constant.  Then
2212 when @code{strtok} or @code{wcstok} tries to modify it, your program
2213 will get a fatal signal for writing in read-only memory.  @xref{Program
2214 Error Signals}.  Even if the operation of @code{strtok} or @code{wcstok}
2215 would not require a modification of the string (e.g., if there is
2216 exactly one token) the string can (and in the @glibcadj{} case will) be
2217 modified.
2219 This is a special case of a general principle: if a part of a program
2220 does not have as its purpose the modification of a certain data
2221 structure, then it is error-prone to modify the data structure
2222 temporarily.
2224 The function @code{strtok} is not reentrant, whereas @code{wcstok} is.
2225 @xref{Nonreentrancy}, for a discussion of where and why reentrancy is
2226 important.
2228 Here is a simple example showing the use of @code{strtok}.
2230 @comment Yes, this example has been tested.
2231 @smallexample
2232 #include <string.h>
2233 #include <stddef.h>
2235 @dots{}
2237 const char string[] = "words separated by spaces -- and, punctuation!";
2238 const char delimiters[] = " .,;:!-";
2239 char *token, *cp;
2241 @dots{}
2243 cp = strdupa (string);                /* Make writable copy.  */
2244 token = strtok (cp, delimiters);      /* token => "words" */
2245 token = strtok (NULL, delimiters);    /* token => "separated" */
2246 token = strtok (NULL, delimiters);    /* token => "by" */
2247 token = strtok (NULL, delimiters);    /* token => "spaces" */
2248 token = strtok (NULL, delimiters);    /* token => "and" */
2249 token = strtok (NULL, delimiters);    /* token => "punctuation" */
2250 token = strtok (NULL, delimiters);    /* token => NULL */
2251 @end smallexample
2253 @Theglibc{} contains two more functions for tokenizing a string
2254 which overcome the limitation of non-reentrancy.  They are not
2255 available available for wide strings.
2257 @comment string.h
2258 @comment POSIX
2259 @deftypefun {char *} strtok_r (char *@var{newstring}, const char *@var{delimiters}, char **@var{save_ptr})
2260 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2261 Just like @code{strtok}, this function splits the string into several
2262 tokens which can be accessed by successive calls to @code{strtok_r}.
2263 The difference is that, as in @code{wcstok}, the information about the
2264 next token is stored in the space pointed to by the third argument,
2265 @var{save_ptr}, which is a pointer to a string pointer.  Calling
2266 @code{strtok_r} with a null pointer for @var{newstring} and leaving
2267 @var{save_ptr} between the calls unchanged does the job without
2268 hindering reentrancy.
2270 This function is defined in POSIX.1 and can be found on many systems
2271 which support multi-threading.
2272 @end deftypefun
2274 @comment string.h
2275 @comment BSD
2276 @deftypefun {char *} strsep (char **@var{string_ptr}, const char *@var{delimiter})
2277 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2278 This function has a similar functionality as @code{strtok_r} with the
2279 @var{newstring} argument replaced by the @var{save_ptr} argument.  The
2280 initialization of the moving pointer has to be done by the user.
2281 Successive calls to @code{strsep} move the pointer along the tokens
2282 separated by @var{delimiter}, returning the address of the next token
2283 and updating @var{string_ptr} to point to the beginning of the next
2284 token.
2286 One difference between @code{strsep} and @code{strtok_r} is that if the
2287 input string contains more than one byte from @var{delimiter} in a
2288 row @code{strsep} returns an empty string for each pair of bytes
2289 from @var{delimiter}.  This means that a program normally should test
2290 for @code{strsep} returning an empty string before processing it.
2292 This function was introduced in 4.3BSD and therefore is widely available.
2293 @end deftypefun
2295 Here is how the above example looks like when @code{strsep} is used.
2297 @comment Yes, this example has been tested.
2298 @smallexample
2299 #include <string.h>
2300 #include <stddef.h>
2302 @dots{}
2304 const char string[] = "words separated by spaces -- and, punctuation!";
2305 const char delimiters[] = " .,;:!-";
2306 char *running;
2307 char *token;
2309 @dots{}
2311 running = strdupa (string);
2312 token = strsep (&running, delimiters);    /* token => "words" */
2313 token = strsep (&running, delimiters);    /* token => "separated" */
2314 token = strsep (&running, delimiters);    /* token => "by" */
2315 token = strsep (&running, delimiters);    /* token => "spaces" */
2316 token = strsep (&running, delimiters);    /* token => "" */
2317 token = strsep (&running, delimiters);    /* token => "" */
2318 token = strsep (&running, delimiters);    /* token => "" */
2319 token = strsep (&running, delimiters);    /* token => "and" */
2320 token = strsep (&running, delimiters);    /* token => "" */
2321 token = strsep (&running, delimiters);    /* token => "punctuation" */
2322 token = strsep (&running, delimiters);    /* token => "" */
2323 token = strsep (&running, delimiters);    /* token => NULL */
2324 @end smallexample
2326 @comment string.h
2327 @comment GNU
2328 @deftypefun {char *} basename (const char *@var{filename})
2329 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2330 The GNU version of the @code{basename} function returns the last
2331 component of the path in @var{filename}.  This function is the preferred
2332 usage, since it does not modify the argument, @var{filename}, and
2333 respects trailing slashes.  The prototype for @code{basename} can be
2334 found in @file{string.h}.  Note, this function is overridden by the XPG
2335 version, if @file{libgen.h} is included.
2337 Example of using GNU @code{basename}:
2339 @smallexample
2340 #include <string.h>
2343 main (int argc, char *argv[])
2345   char *prog = basename (argv[0]);
2347   if (argc < 2)
2348     @{
2349       fprintf (stderr, "Usage %s <arg>\n", prog);
2350       exit (1);
2351     @}
2353   @dots{}
2355 @end smallexample
2357 @strong{Portability Note:} This function may produce different results
2358 on different systems.
2360 @end deftypefun
2362 @comment libgen.h
2363 @comment XPG
2364 @deftypefun {char *} basename (char *@var{path})
2365 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2366 This is the standard XPG defined @code{basename}.  It is similar in
2367 spirit to the GNU version, but may modify the @var{path} by removing
2368 trailing '/' bytes.  If the @var{path} is made up entirely of '/'
2369 bytes, then "/" will be returned.  Also, if @var{path} is
2370 @code{NULL} or an empty string, then "." is returned.  The prototype for
2371 the XPG version can be found in @file{libgen.h}.
2373 Example of using XPG @code{basename}:
2375 @smallexample
2376 #include <libgen.h>
2379 main (int argc, char *argv[])
2381   char *prog;
2382   char *path = strdupa (argv[0]);
2384   prog = basename (path);
2386   if (argc < 2)
2387     @{
2388       fprintf (stderr, "Usage %s <arg>\n", prog);
2389       exit (1);
2390     @}
2392   @dots{}
2395 @end smallexample
2396 @end deftypefun
2398 @comment libgen.h
2399 @comment XPG
2400 @deftypefun {char *} dirname (char *@var{path})
2401 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2402 The @code{dirname} function is the compliment to the XPG version of
2403 @code{basename}.  It returns the parent directory of the file specified
2404 by @var{path}.  If @var{path} is @code{NULL}, an empty string, or
2405 contains no '/' bytes, then "." is returned.  The prototype for this
2406 function can be found in @file{libgen.h}.
2407 @end deftypefun
2409 @node Erasing Sensitive Data
2410 @section Erasing Sensitive Data
2412 Sensitive data, such as cryptographic keys, should be erased from
2413 memory after use, to reduce the risk that a bug will expose it to the
2414 outside world.  However, compiler optimizations may determine that an
2415 erasure operation is ``unnecessary,'' and remove it from the generated
2416 code, because no @emph{correct} program could access the variable or
2417 heap object containing the sensitive data after it's deallocated.
2418 Since erasure is a precaution against bugs, this optimization is
2419 inappropriate.
2421 The function @code{explicit_bzero} erases a block of memory, and
2422 guarantees that the compiler will not remove the erasure as
2423 ``unnecessary.''
2425 @smallexample
2426 @group
2427 #include <string.h>
2429 extern void encrypt (const char *key, const char *in,
2430                      char *out, size_t n);
2431 extern void genkey (const char *phrase, char *key);
2433 void encrypt_with_phrase (const char *phrase, const char *in,
2434                           char *out, size_t n)
2436   char key[16];
2437   genkey (phrase, key);
2438   encrypt (key, in, out, n);
2439   explicit_bzero (key, 16);
2441 @end group
2442 @end smallexample
2444 @noindent
2445 In this example, if @code{memset}, @code{bzero}, or a hand-written
2446 loop had been used, the compiler might remove them as ``unnecessary.''
2448 @strong{Warning:} @code{explicit_bzero} does not guarantee that
2449 sensitive data is @emph{completely} erased from the computer's memory.
2450 There may be copies in temporary storage areas, such as registers and
2451 ``scratch'' stack space; since these are invisible to the source code,
2452 a library function cannot erase them.
2454 Also, @code{explicit_bzero} only operates on RAM.  If a sensitive data
2455 object never needs to have its address taken other than to call
2456 @code{explicit_bzero}, it might be stored entirely in CPU registers
2457 @emph{until} the call to @code{explicit_bzero}.  Then it will be
2458 copied into RAM, the copy will be erased, and the original will remain
2459 intact.  Data in RAM is more likely to be exposed by a bug than data
2460 in registers, so this creates a brief window where the data is at
2461 greater risk of exposure than it would have been if the program didn't
2462 try to erase it at all.
2464 Declaring sensitive variables as @code{volatile} will make both the
2465 above problems @emph{worse}; a @code{volatile} variable will be stored
2466 in memory for its entire lifetime, and the compiler will make
2467 @emph{more} copies of it than it would otherwise have.  Attempting to
2468 erase a normal variable ``by hand'' through a
2469 @code{volatile}-qualified pointer doesn't work at all---because the
2470 variable itself is not @code{volatile}, some compilers will ignore the
2471 qualification on the pointer and remove the erasure anyway.
2473 Having said all that, in most situations, using @code{explicit_bzero}
2474 is better than not using it.  At present, the only way to do a more
2475 thorough job is to write the entire sensitive operation in assembly
2476 language.  We anticipate that future compilers will recognize calls to
2477 @code{explicit_bzero} and take appropriate steps to erase all the
2478 copies of the affected data, whereever they may be.
2480 @comment string.h
2481 @comment BSD
2482 @deftypefun void explicit_bzero (void *@var{block}, size_t @var{len})
2483 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2485 @code{explicit_bzero} writes zero into @var{len} bytes of memory
2486 beginning at @var{block}, just as @code{bzero} would.  The zeroes are
2487 always written, even if the compiler could determine that this is
2488 ``unnecessary'' because no correct program could read them back.
2490 @strong{Note:} The @emph{only} optimization that @code{explicit_bzero}
2491 disables is removal of ``unnecessary'' writes to memory.  The compiler
2492 can perform all the other optimizations that it could for a call to
2493 @code{memset}.  For instance, it may replace the function call with
2494 inline memory writes, and it may assume that @var{block} cannot be a
2495 null pointer.
2497 @strong{Portability Note:} This function first appeared in OpenBSD 5.5
2498 and has not been standardized.  Other systems may provide the same
2499 functionality under a different name, such as @code{explicit_memset},
2500 @code{memset_s}, or @code{SecureZeroMemory}.
2502 @Theglibc{} declares this function in @file{string.h}, but on other
2503 systems it may be in @file{strings.h} instead.
2504 @end deftypefun
2506 @node strfry
2507 @section strfry
2509 The function below addresses the perennial programming quandary: ``How do
2510 I take good data in string form and painlessly turn it into garbage?''
2511 This is actually a fairly simple task for C programmers who do not use
2512 @theglibc{} string functions, but for programs based on @theglibc{},
2513 the @code{strfry} function is the preferred method for
2514 destroying string data.
2516 The prototype for this function is in @file{string.h}.
2518 @comment string.h
2519 @comment GNU
2520 @deftypefun {char *} strfry (char *@var{string})
2521 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2522 @c Calls initstate_r, time, getpid, strlen, and random_r.
2524 @code{strfry} creates a pseudorandom anagram of a string, replacing the
2525 input with the anagram in place.  For each position in the string,
2526 @code{strfry} swaps it with a position in the string selected at random
2527 (from a uniform distribution).  The two positions may be the same.
2529 The return value of @code{strfry} is always @var{string}.
2531 @strong{Portability Note:}  This function is unique to @theglibc{}.
2533 @end deftypefun
2536 @node Trivial Encryption
2537 @section Trivial Encryption
2538 @cindex encryption
2541 The @code{memfrob} function converts an array of data to something
2542 unrecognizable and back again.  It is not encryption in its usual sense
2543 since it is easy for someone to convert the encrypted data back to clear
2544 text.  The transformation is analogous to Usenet's ``Rot13'' encryption
2545 method for obscuring offensive jokes from sensitive eyes and such.
2546 Unlike Rot13, @code{memfrob} works on arbitrary binary data, not just
2547 text.
2548 @cindex Rot13
2550 For true encryption, @xref{Cryptographic Functions}.
2552 This function is declared in @file{string.h}.
2553 @pindex string.h
2555 @comment string.h
2556 @comment GNU
2557 @deftypefun {void *} memfrob (void *@var{mem}, size_t @var{length})
2558 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2560 @code{memfrob} transforms (frobnicates) each byte of the data structure
2561 at @var{mem}, which is @var{length} bytes long, by bitwise exclusive
2562 oring it with binary 00101010.  It does the transformation in place and
2563 its return value is always @var{mem}.
2565 Note that @code{memfrob} a second time on the same data structure
2566 returns it to its original state.
2568 This is a good function for hiding information from someone who doesn't
2569 want to see it or doesn't want to see it very much.  To really prevent
2570 people from retrieving the information, use stronger encryption such as
2571 that described in @xref{Cryptographic Functions}.
2573 @strong{Portability Note:}  This function is unique to @theglibc{}.
2575 @end deftypefun
2577 @node Encode Binary Data
2578 @section Encode Binary Data
2580 To store or transfer binary data in environments which only support text
2581 one has to encode the binary data by mapping the input bytes to
2582 bytes in the range allowed for storing or transferring.  SVID
2583 systems (and nowadays XPG compliant systems) provide minimal support for
2584 this task.
2586 @comment stdlib.h
2587 @comment XPG
2588 @deftypefun {char *} l64a (long int @var{n})
2589 @safety{@prelim{}@mtunsafe{@mtasurace{:l64a}}@asunsafe{}@acsafe{}}
2590 This function encodes a 32-bit input value using bytes from the
2591 basic character set.  It returns a pointer to a 7 byte buffer which
2592 contains an encoded version of @var{n}.  To encode a series of bytes the
2593 user must copy the returned string to a destination buffer.  It returns
2594 the empty string if @var{n} is zero, which is somewhat bizarre but
2595 mandated by the standard.@*
2596 @strong{Warning:} Since a static buffer is used this function should not
2597 be used in multi-threaded programs.  There is no thread-safe alternative
2598 to this function in the C library.@*
2599 @strong{Compatibility Note:} The XPG standard states that the return
2600 value of @code{l64a} is undefined if @var{n} is negative.  In the GNU
2601 implementation, @code{l64a} treats its argument as unsigned, so it will
2602 return a sensible encoding for any nonzero @var{n}; however, portable
2603 programs should not rely on this.
2605 To encode a large buffer @code{l64a} must be called in a loop, once for
2606 each 32-bit word of the buffer.  For example, one could do something
2607 like this:
2609 @smallexample
2610 char *
2611 encode (const void *buf, size_t len)
2613   /* @r{We know in advance how long the buffer has to be.} */
2614   unsigned char *in = (unsigned char *) buf;
2615   char *out = malloc (6 + ((len + 3) / 4) * 6 + 1);
2616   char *cp = out, *p;
2618   /* @r{Encode the length.} */
2619   /* @r{Using `htonl' is necessary so that the data can be}
2620      @r{decoded even on machines with different byte order.}
2621      @r{`l64a' can return a string shorter than 6 bytes, so }
2622      @r{we pad it with encoding of 0 (}'.'@r{) at the end by }
2623      @r{hand.} */
2625   p = stpcpy (cp, l64a (htonl (len)));
2626   cp = mempcpy (p, "......", 6 - (p - cp));
2628   while (len > 3)
2629     @{
2630       unsigned long int n = *in++;
2631       n = (n << 8) | *in++;
2632       n = (n << 8) | *in++;
2633       n = (n << 8) | *in++;
2634       len -= 4;
2635       p = stpcpy (cp, l64a (htonl (n)));
2636       cp = mempcpy (p, "......", 6 - (p - cp));
2637     @}
2638   if (len > 0)
2639     @{
2640       unsigned long int n = *in++;
2641       if (--len > 0)
2642         @{
2643           n = (n << 8) | *in++;
2644           if (--len > 0)
2645             n = (n << 8) | *in;
2646         @}
2647       cp = stpcpy (cp, l64a (htonl (n)));
2648     @}
2649   *cp = '\0';
2650   return out;
2652 @end smallexample
2654 It is strange that the library does not provide the complete
2655 functionality needed but so be it.
2657 @end deftypefun
2659 To decode data produced with @code{l64a} the following function should be
2660 used.
2662 @comment stdlib.h
2663 @comment XPG
2664 @deftypefun {long int} a64l (const char *@var{string})
2665 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2666 The parameter @var{string} should contain a string which was produced by
2667 a call to @code{l64a}.  The function processes at least 6 bytes of
2668 this string, and decodes the bytes it finds according to the table
2669 below.  It stops decoding when it finds a byte not in the table,
2670 rather like @code{atoi}; if you have a buffer which has been broken into
2671 lines, you must be careful to skip over the end-of-line bytes.
2673 The decoded number is returned as a @code{long int} value.
2674 @end deftypefun
2676 The @code{l64a} and @code{a64l} functions use a base 64 encoding, in
2677 which each byte of an encoded string represents six bits of an
2678 input word.  These symbols are used for the base 64 digits:
2680 @multitable {xxxxx} {xxx} {xxx} {xxx} {xxx} {xxx} {xxx} {xxx} {xxx}
2681 @item              @tab 0 @tab 1 @tab 2 @tab 3 @tab 4 @tab 5 @tab 6 @tab 7
2682 @item       0      @tab @code{.} @tab @code{/} @tab @code{0} @tab @code{1}
2683                    @tab @code{2} @tab @code{3} @tab @code{4} @tab @code{5}
2684 @item       8      @tab @code{6} @tab @code{7} @tab @code{8} @tab @code{9}
2685                    @tab @code{A} @tab @code{B} @tab @code{C} @tab @code{D}
2686 @item       16     @tab @code{E} @tab @code{F} @tab @code{G} @tab @code{H}
2687                    @tab @code{I} @tab @code{J} @tab @code{K} @tab @code{L}
2688 @item       24     @tab @code{M} @tab @code{N} @tab @code{O} @tab @code{P}
2689                    @tab @code{Q} @tab @code{R} @tab @code{S} @tab @code{T}
2690 @item       32     @tab @code{U} @tab @code{V} @tab @code{W} @tab @code{X}
2691                    @tab @code{Y} @tab @code{Z} @tab @code{a} @tab @code{b}
2692 @item       40     @tab @code{c} @tab @code{d} @tab @code{e} @tab @code{f}
2693                    @tab @code{g} @tab @code{h} @tab @code{i} @tab @code{j}
2694 @item       48     @tab @code{k} @tab @code{l} @tab @code{m} @tab @code{n}
2695                    @tab @code{o} @tab @code{p} @tab @code{q} @tab @code{r}
2696 @item       56     @tab @code{s} @tab @code{t} @tab @code{u} @tab @code{v}
2697                    @tab @code{w} @tab @code{x} @tab @code{y} @tab @code{z}
2698 @end multitable
2700 This encoding scheme is not standard.  There are some other encoding
2701 methods which are much more widely used (UU encoding, MIME encoding).
2702 Generally, it is better to use one of these encodings.
2704 @node Argz and Envz Vectors
2705 @section Argz and Envz Vectors
2707 @cindex argz vectors (string vectors)
2708 @cindex string vectors, null-byte separated
2709 @cindex argument vectors, null-byte separated
2710 @dfn{argz vectors} are vectors of strings in a contiguous block of
2711 memory, each element separated from its neighbors by null bytes
2712 (@code{'\0'}).
2714 @cindex envz vectors (environment vectors)
2715 @cindex environment vectors, null-byte separated
2716 @dfn{Envz vectors} are an extension of argz vectors where each element is a
2717 name-value pair, separated by a @code{'='} byte (as in a Unix
2718 environment).
2720 @menu
2721 * Argz Functions::              Operations on argz vectors.
2722 * Envz Functions::              Additional operations on environment vectors.
2723 @end menu
2725 @node Argz Functions, Envz Functions, , Argz and Envz Vectors
2726 @subsection Argz Functions
2728 Each argz vector is represented by a pointer to the first element, of
2729 type @code{char *}, and a size, of type @code{size_t}, both of which can
2730 be initialized to @code{0} to represent an empty argz vector.  All argz
2731 functions accept either a pointer and a size argument, or pointers to
2732 them, if they will be modified.
2734 The argz functions use @code{malloc}/@code{realloc} to allocate/grow
2735 argz vectors, and so any argz vector created using these functions may
2736 be freed by using @code{free}; conversely, any argz function that may
2737 grow a string expects that string to have been allocated using
2738 @code{malloc} (those argz functions that only examine their arguments or
2739 modify them in place will work on any sort of memory).
2740 @xref{Unconstrained Allocation}.
2742 All argz functions that do memory allocation have a return type of
2743 @code{error_t}, and return @code{0} for success, and @code{ENOMEM} if an
2744 allocation error occurs.
2746 @pindex argz.h
2747 These functions are declared in the standard include file @file{argz.h}.
2749 @comment argz.h
2750 @comment GNU
2751 @deftypefun {error_t} argz_create (char *const @var{argv}[], char **@var{argz}, size_t *@var{argz_len})
2752 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
2753 The @code{argz_create} function converts the Unix-style argument vector
2754 @var{argv} (a vector of pointers to normal C strings, terminated by
2755 @code{(char *)0}; @pxref{Program Arguments}) into an argz vector with
2756 the same elements, which is returned in @var{argz} and @var{argz_len}.
2757 @end deftypefun
2759 @comment argz.h
2760 @comment GNU
2761 @deftypefun {error_t} argz_create_sep (const char *@var{string}, int @var{sep}, char **@var{argz}, size_t *@var{argz_len})
2762 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
2763 The @code{argz_create_sep} function converts the string
2764 @var{string} into an argz vector (returned in @var{argz} and
2765 @var{argz_len}) by splitting it into elements at every occurrence of the
2766 byte @var{sep}.
2767 @end deftypefun
2769 @comment argz.h
2770 @comment GNU
2771 @deftypefun {size_t} argz_count (const char *@var{argz}, size_t @var{argz_len})
2772 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2773 Returns the number of elements in the argz vector @var{argz} and
2774 @var{argz_len}.
2775 @end deftypefun
2777 @comment argz.h
2778 @comment GNU
2779 @deftypefun {void} argz_extract (const char *@var{argz}, size_t @var{argz_len}, char **@var{argv})
2780 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2781 The @code{argz_extract} function converts the argz vector @var{argz} and
2782 @var{argz_len} into a Unix-style argument vector stored in @var{argv},
2783 by putting pointers to every element in @var{argz} into successive
2784 positions in @var{argv}, followed by a terminator of @code{0}.
2785 @var{Argv} must be pre-allocated with enough space to hold all the
2786 elements in @var{argz} plus the terminating @code{(char *)0}
2787 (@code{(argz_count (@var{argz}, @var{argz_len}) + 1) * sizeof (char *)}
2788 bytes should be enough).  Note that the string pointers stored into
2789 @var{argv} point into @var{argz}---they are not copies---and so
2790 @var{argz} must be copied if it will be changed while @var{argv} is
2791 still active.  This function is useful for passing the elements in
2792 @var{argz} to an exec function (@pxref{Executing a File}).
2793 @end deftypefun
2795 @comment argz.h
2796 @comment GNU
2797 @deftypefun {void} argz_stringify (char *@var{argz}, size_t @var{len}, int @var{sep})
2798 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2799 The @code{argz_stringify} converts @var{argz} into a normal string with
2800 the elements separated by the byte @var{sep}, by replacing each
2801 @code{'\0'} inside @var{argz} (except the last one, which terminates the
2802 string) with @var{sep}.  This is handy for printing @var{argz} in a
2803 readable manner.
2804 @end deftypefun
2806 @comment argz.h
2807 @comment GNU
2808 @deftypefun {error_t} argz_add (char **@var{argz}, size_t *@var{argz_len}, const char *@var{str})
2809 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
2810 @c Calls strlen and argz_append.
2811 The @code{argz_add} function adds the string @var{str} to the end of the
2812 argz vector @code{*@var{argz}}, and updates @code{*@var{argz}} and
2813 @code{*@var{argz_len}} accordingly.
2814 @end deftypefun
2816 @comment argz.h
2817 @comment GNU
2818 @deftypefun {error_t} argz_add_sep (char **@var{argz}, size_t *@var{argz_len}, const char *@var{str}, int @var{delim})
2819 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
2820 The @code{argz_add_sep} function is similar to @code{argz_add}, but
2821 @var{str} is split into separate elements in the result at occurrences of
2822 the byte @var{delim}.  This is useful, for instance, for
2823 adding the components of a Unix search path to an argz vector, by using
2824 a value of @code{':'} for @var{delim}.
2825 @end deftypefun
2827 @comment argz.h
2828 @comment GNU
2829 @deftypefun {error_t} argz_append (char **@var{argz}, size_t *@var{argz_len}, const char *@var{buf}, size_t @var{buf_len})
2830 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
2831 The @code{argz_append} function appends @var{buf_len} bytes starting at
2832 @var{buf} to the argz vector @code{*@var{argz}}, reallocating
2833 @code{*@var{argz}} to accommodate it, and adding @var{buf_len} to
2834 @code{*@var{argz_len}}.
2835 @end deftypefun
2837 @comment argz.h
2838 @comment GNU
2839 @deftypefun {void} argz_delete (char **@var{argz}, size_t *@var{argz_len}, char *@var{entry})
2840 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
2841 @c Calls free if no argument is left.
2842 If @var{entry} points to the beginning of one of the elements in the
2843 argz vector @code{*@var{argz}}, the @code{argz_delete} function will
2844 remove this entry and reallocate @code{*@var{argz}}, modifying
2845 @code{*@var{argz}} and @code{*@var{argz_len}} accordingly.  Note that as
2846 destructive argz functions usually reallocate their argz argument,
2847 pointers into argz vectors such as @var{entry} will then become invalid.
2848 @end deftypefun
2850 @comment argz.h
2851 @comment GNU
2852 @deftypefun {error_t} argz_insert (char **@var{argz}, size_t *@var{argz_len}, char *@var{before}, const char *@var{entry})
2853 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
2854 @c Calls argz_add or realloc and memmove.
2855 The @code{argz_insert} function inserts the string @var{entry} into the
2856 argz vector @code{*@var{argz}} at a point just before the existing
2857 element pointed to by @var{before}, reallocating @code{*@var{argz}} and
2858 updating @code{*@var{argz}} and @code{*@var{argz_len}}.  If @var{before}
2859 is @code{0}, @var{entry} is added to the end instead (as if by
2860 @code{argz_add}).  Since the first element is in fact the same as
2861 @code{*@var{argz}}, passing in @code{*@var{argz}} as the value of
2862 @var{before} will result in @var{entry} being inserted at the beginning.
2863 @end deftypefun
2865 @comment argz.h
2866 @comment GNU
2867 @deftypefun {char *} argz_next (const char *@var{argz}, size_t @var{argz_len}, const char *@var{entry})
2868 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2869 The @code{argz_next} function provides a convenient way of iterating
2870 over the elements in the argz vector @var{argz}.  It returns a pointer
2871 to the next element in @var{argz} after the element @var{entry}, or
2872 @code{0} if there are no elements following @var{entry}.  If @var{entry}
2873 is @code{0}, the first element of @var{argz} is returned.
2875 This behavior suggests two styles of iteration:
2877 @smallexample
2878     char *entry = 0;
2879     while ((entry = argz_next (@var{argz}, @var{argz_len}, entry)))
2880       @var{action};
2881 @end smallexample
2883 (the double parentheses are necessary to make some C compilers shut up
2884 about what they consider a questionable @code{while}-test) and:
2886 @smallexample
2887     char *entry;
2888     for (entry = @var{argz};
2889          entry;
2890          entry = argz_next (@var{argz}, @var{argz_len}, entry))
2891       @var{action};
2892 @end smallexample
2894 Note that the latter depends on @var{argz} having a value of @code{0} if
2895 it is empty (rather than a pointer to an empty block of memory); this
2896 invariant is maintained for argz vectors created by the functions here.
2897 @end deftypefun
2899 @comment argz.h
2900 @comment GNU
2901 @deftypefun error_t argz_replace (@w{char **@var{argz}, size_t *@var{argz_len}}, @w{const char *@var{str}, const char *@var{with}}, @w{unsigned *@var{replace_count}})
2902 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
2903 Replace any occurrences of the string @var{str} in @var{argz} with
2904 @var{with}, reallocating @var{argz} as necessary.  If
2905 @var{replace_count} is non-zero, @code{*@var{replace_count}} will be
2906 incremented by the number of replacements performed.
2907 @end deftypefun
2909 @node Envz Functions, , Argz Functions, Argz and Envz Vectors
2910 @subsection Envz Functions
2912 Envz vectors are just argz vectors with additional constraints on the form
2913 of each element; as such, argz functions can also be used on them, where it
2914 makes sense.
2916 Each element in an envz vector is a name-value pair, separated by a @code{'='}
2917 byte; if multiple @code{'='} bytes are present in an element, those
2918 after the first are considered part of the value, and treated like all other
2919 non-@code{'\0'} bytes.
2921 If @emph{no} @code{'='} bytes are present in an element, that element is
2922 considered the name of a ``null'' entry, as distinct from an entry with an
2923 empty value: @code{envz_get} will return @code{0} if given the name of null
2924 entry, whereas an entry with an empty value would result in a value of
2925 @code{""}; @code{envz_entry} will still find such entries, however.  Null
2926 entries can be removed with the @code{envz_strip} function.
2928 As with argz functions, envz functions that may allocate memory (and thus
2929 fail) have a return type of @code{error_t}, and return either @code{0} or
2930 @code{ENOMEM}.
2932 @pindex envz.h
2933 These functions are declared in the standard include file @file{envz.h}.
2935 @comment envz.h
2936 @comment GNU
2937 @deftypefun {char *} envz_entry (const char *@var{envz}, size_t @var{envz_len}, const char *@var{name})
2938 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2939 The @code{envz_entry} function finds the entry in @var{envz} with the name
2940 @var{name}, and returns a pointer to the whole entry---that is, the argz
2941 element which begins with @var{name} followed by a @code{'='} byte.  If
2942 there is no entry with that name, @code{0} is returned.
2943 @end deftypefun
2945 @comment envz.h
2946 @comment GNU
2947 @deftypefun {char *} envz_get (const char *@var{envz}, size_t @var{envz_len}, const char *@var{name})
2948 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2949 The @code{envz_get} function finds the entry in @var{envz} with the name
2950 @var{name} (like @code{envz_entry}), and returns a pointer to the value
2951 portion of that entry (following the @code{'='}).  If there is no entry with
2952 that name (or only a null entry), @code{0} is returned.
2953 @end deftypefun
2955 @comment envz.h
2956 @comment GNU
2957 @deftypefun {error_t} envz_add (char **@var{envz}, size_t *@var{envz_len}, const char *@var{name}, const char *@var{value})
2958 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
2959 @c Calls envz_remove, which calls enz_entry and argz_delete, and then
2960 @c argz_add or equivalent code that reallocs and appends name=value.
2961 The @code{envz_add} function adds an entry to @code{*@var{envz}}
2962 (updating @code{*@var{envz}} and @code{*@var{envz_len}}) with the name
2963 @var{name}, and value @var{value}.  If an entry with the same name
2964 already exists in @var{envz}, it is removed first.  If @var{value} is
2965 @code{0}, then the new entry will be the special null type of entry
2966 (mentioned above).
2967 @end deftypefun
2969 @comment envz.h
2970 @comment GNU
2971 @deftypefun {error_t} envz_merge (char **@var{envz}, size_t *@var{envz_len}, const char *@var{envz2}, size_t @var{envz2_len}, int @var{override})
2972 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
2973 The @code{envz_merge} function adds each entry in @var{envz2} to @var{envz},
2974 as if with @code{envz_add}, updating @code{*@var{envz}} and
2975 @code{*@var{envz_len}}.  If @var{override} is true, then values in @var{envz2}
2976 will supersede those with the same name in @var{envz}, otherwise not.
2978 Null entries are treated just like other entries in this respect, so a null
2979 entry in @var{envz} can prevent an entry of the same name in @var{envz2} from
2980 being added to @var{envz}, if @var{override} is false.
2981 @end deftypefun
2983 @comment envz.h
2984 @comment GNU
2985 @deftypefun {void} envz_strip (char **@var{envz}, size_t *@var{envz_len})
2986 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2987 The @code{envz_strip} function removes any null entries from @var{envz},
2988 updating @code{*@var{envz}} and @code{*@var{envz_len}}.
2989 @end deftypefun
2991 @comment envz.h
2992 @comment GNU
2993 @deftypefun {void} envz_remove (char **@var{envz}, size_t *@var{envz_len}, const char *@var{name})
2994 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
2995 The @code{envz_remove} function removes an entry named @var{name} from
2996 @var{envz}, updating @code{*@var{envz}} and @code{*@var{envz_len}}.
2997 @end deftypefun
2999 @c FIXME this are undocumented:
3000 @c strcasecmp_l @safety{@mtsafe{}@assafe{}@acsafe{}} see strcasecmp