This is Info file libc.info, produced by Makeinfo version 1.68 from the
input file libc.texinfo.

INFO-DIR-SECTION GNU libraries
START-INFO-DIR-ENTRY
* Libc: (libc).                 C library.
END-INFO-DIR-ENTRY

   This file documents the GNU C library.

   This is Edition 0.08 DRAFT, last updated 11 Jan 1999, of `The GNU C
Library Reference Manual', for Version 2.1 Beta.

   Copyright (C) 1993, '94, '95, '96, '97, '98, '99 Free Software
Foundation, Inc.

   Permission is granted to make and distribute verbatim copies of this
manual provided the copyright notice and this permission notice are
preserved on all copies.

   Permission is granted to copy and distribute modified versions of
this manual under the conditions for verbatim copying, provided also
that the section entitled "GNU Library General Public License" is
included exactly as in the original, and provided that the entire
resulting derived work is distributed under the terms of a permission
notice identical to this one.

   Permission is granted to copy and distribute translations of this
manual into another language, under the above conditions for modified
versions, except that the text of the translation of the section
entitled "GNU Library General Public License" must be approved for
accuracy by the Foundation.


File: libc.info,  Node: Alloca Example,  Next: Advantages of Alloca,  Up: Variable Size Automatic

`alloca' Example
----------------

   As an example of use of `alloca', here is a function that opens a
file name made from concatenating two argument strings, and returns a
file descriptor or minus one signifying failure:

     int
     open2 (char *str1, char *str2, int flags, int mode)
     {
       char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
       stpcpy (stpcpy (name, str1), str2);
       return open (name, flags, mode);
     }

Here is how you would get the same results with `malloc' and `free':

     int
     open2 (char *str1, char *str2, int flags, int mode)
     {
       char *name = (char *) malloc (strlen (str1) + strlen (str2) + 1);
       int desc;
       if (name == 0)
         fatal ("virtual memory exceeded");
       stpcpy (stpcpy (name, str1), str2);
       desc = open (name, flags, mode);
       free (name);
       return desc;
     }

   As you can see, it is simpler with `alloca'.  But `alloca' has
other, more important advantages, and some disadvantages.


File: libc.info,  Node: Advantages of Alloca,  Next: Disadvantages of Alloca,  Prev: Alloca Example,  Up: Variable Size Automatic

Advantages of `alloca'
----------------------

   Here are the reasons why `alloca' may be preferable to `malloc':

   * Using `alloca' wastes very little space and is very fast.  (It is
     open-coded by the GNU C compiler.)

   * Since `alloca' does not have separate pools for different sizes of
     block, space used for any size block can be reused for any other
     size.  `alloca' does not cause storage fragmentation.

   * Nonlocal exits done with `longjmp' (*note Non-Local Exits::.)
     automatically free the space allocated with `alloca' when they exit
     through the function that called `alloca'.  This is the most
     important reason to use `alloca'.

     To illustrate this, suppose you have a function
     `open_or_report_error' which returns a descriptor, like `open', if
     it succeeds, but does not return to its caller if it fails.  If
     the file cannot be opened, it prints an error message and jumps
     out to the command level of your program using `longjmp'.  Let's
     change `open2' (*note Alloca Example::.) to use this subroutine:

          int
          open2 (char *str1, char *str2, int flags, int mode)
          {
            char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
            stpcpy (stpcpy (name, str1), str2);
            return open_or_report_error (name, flags, mode);
          }

     Because of the way `alloca' works, the storage it allocates is
     freed even when an error occurs, with no special effort required.

     By contrast, the previous definition of `open2' (which uses
     `malloc' and `free') would develop a storage leak if it were
     changed in this way.  Even if you are willing to make more changes
     to fix it, there is no easy way to do so.


File: libc.info,  Node: Disadvantages of Alloca,  Next: GNU C Variable-Size Arrays,  Prev: Advantages of Alloca,  Up: Variable Size Automatic

Disadvantages of `alloca'
-------------------------

   These are the disadvantages of `alloca' in comparison with `malloc':

   * If you try to allocate more storage than the machine can provide,
     you don't get a clean error message.  Instead you get a fatal
     signal like the one you would get from an infinite recursion;
     probably a segmentation violation (*note Program Error Signals::.).

   * Some non-GNU systems fail to support `alloca', so it is less
     portable.  However, a slower emulation of `alloca' written in C is
     available for use on systems with this deficiency.


File: libc.info,  Node: GNU C Variable-Size Arrays,  Prev: Disadvantages of Alloca,  Up: Variable Size Automatic

GNU C Variable-Size Arrays
--------------------------

   In GNU C, you can replace most uses of `alloca' with an array of
variable size.  Here is how `open2' would look then:

     int open2 (char *str1, char *str2, int flags, int mode)
     {
       char name[strlen (str1) + strlen (str2) + 1];
       stpcpy (stpcpy (name, str1), str2);
       return open (name, flags, mode);
     }

   But `alloca' is not always equivalent to a variable-sized array, for
several reasons:

   * A variable size array's space is freed at the end of the scope of
     the name of the array.  The space allocated with `alloca' remains
     until the end of the function.

   * It is possible to use `alloca' within a loop, allocating an
     additional block on each iteration.  This is impossible with
     variable-sized arrays.

   *Note:* If you mix use of `alloca' and variable-sized arrays within
one function, exiting a scope in which a variable-sized array was
declared frees all blocks allocated with `alloca' during the execution
of that scope.


File: libc.info,  Node: Character Handling,  Next: String and Array Utilities,  Prev: Memory Allocation,  Up: Top

Character Handling
******************

   Programs that work with characters and strings often need to
classify a character--is it alphabetic, is it a digit, is it
whitespace, and so on--and perform case conversion operations on
characters.  The functions in the header file `ctype.h' are provided
for this purpose.

   Since the choice of locale and character set can alter the
classifications of particular character codes, all of these functions
are affected by the current locale.  (More precisely, they are affected
by the locale currently selected for character classification--the
`LC_CTYPE' category; see *Note Locale Categories::.)

   The ISO C standard specifies two different sets of functions.  The
one set works on `char' type characters, the other one on `wchar_t'
wide character (*note Extended Char Intro::.).

* Menu:

* Classification of Characters::       Testing whether characters are
			                letters, digits, punctuation, etc.

* Case Conversion::                    Case mapping, and the like.
* Classification of Wide Characters::  Character class determination for
                                        wide characters.
* Using Wide Char Classes::            Notes on using the wide character
                                        classes.
* Wide Character Case Conversion::     Mapping of wide characters.


File: libc.info,  Node: Classification of Characters,  Next: Case Conversion,  Up: Character Handling

Classification of Characters
============================

   This section explains the library functions for classifying
characters.  For example, `isalpha' is the function to test for an
alphabetic character.  It takes one argument, the character to test,
and returns a nonzero integer if the character is alphabetic, and zero
otherwise.  You would use it like this:

     if (isalpha (c))
       printf ("The character `%c' is alphabetic.\n", c);

   Each of the functions in this section tests for membership in a
particular class of characters; each has a name starting with `is'.
Each of them takes one argument, which is a character to test, and
returns an `int' which is treated as a boolean value.  The character
argument is passed as an `int', and it may be the constant value `EOF'
instead of a real character.

   The attributes of any given character can vary between locales.
*Note Locales::, for more information on locales.

   These functions are declared in the header file `ctype.h'.

 - Function: int islower (int C)
     Returns true if C is a lower-case letter.  The letter need not be
     from the Latin alphabet, any alphabet representable is valid.

 - Function: int isupper (int C)
     Returns true if C is an upper-case letter.  The letter need not be
     from the Latin alphabet, any alphabet representable is valid.

 - Function: int isalpha (int C)
     Returns true if C is an alphabetic character (a letter).  If
     `islower' or `isupper' is true of a character, then `isalpha' is
     also true.

     In some locales, there may be additional characters for which
     `isalpha' is true--letters which are neither upper case nor lower
     case.  But in the standard `"C"' locale, there are no such
     additional characters.

 - Function: int isdigit (int C)
     Returns true if C is a decimal digit (`0' through `9').

 - Function: int isalnum (int C)
     Returns true if C is an alphanumeric character (a letter or
     number); in other words, if either `isalpha' or `isdigit' is true
     of a character, then `isalnum' is also true.

 - Function: int isxdigit (int C)
     Returns true if C is a hexadecimal digit.  Hexadecimal digits
     include the normal decimal digits `0' through `9' and the letters
     `A' through `F' and `a' through `f'.

 - Function: int ispunct (int C)
     Returns true if C is a punctuation character.  This means any
     printing character that is not alphanumeric or a space character.

 - Function: int isspace (int C)
     Returns true if C is a "whitespace" character.  In the standard
     `"C"' locale, `isspace' returns true for only the standard
     whitespace characters:

    `' ''
          space

    `'\f''
          formfeed

    `'\n''
          newline

    `'\r''
          carriage return

    `'\t''
          horizontal tab

    `'\v''
          vertical tab

 - Function: int isblank (int C)
     Returns true if C is a blank character; that is, a space or a tab.
     This function is a GNU extension.

 - Function: int isgraph (int C)
     Returns true if C is a graphic character; that is, a character
     that has a glyph associated with it.  The whitespace characters
     are not considered graphic.

 - Function: int isprint (int C)
     Returns true if C is a printing character.  Printing characters
     include all the graphic characters, plus the space (` ') character.

 - Function: int iscntrl (int C)
     Returns true if C is a control character (that is, a character that
     is not a printing character).

 - Function: int isascii (int C)
     Returns true if C is a 7-bit `unsigned char' value that fits into
     the US/UK ASCII character set.  This function is a BSD extension
     and is also an SVID extension.


File: libc.info,  Node: Case Conversion,  Next: Classification of Wide Characters,  Prev: Classification of Characters,  Up: Character Handling

Case Conversion
===============

   This section explains the library functions for performing
conversions such as case mappings on characters.  For example, `toupper'
converts any character to upper case if possible.  If the character
can't be converted, `toupper' returns it unchanged.

   These functions take one argument of type `int', which is the
character to convert, and return the converted character as an `int'.
If the conversion is not applicable to the argument given, the argument
is returned unchanged.

   *Compatibility Note:* In pre-ISO C dialects, instead of returning
the argument unchanged, these functions may fail when the argument is
not suitable for the conversion.  Thus for portability, you may need to
write `islower(c) ? toupper(c) : c' rather than just `toupper(c)'.

   These functions are declared in the header file `ctype.h'.

 - Function: int tolower (int C)
     If C is an upper-case letter, `tolower' returns the corresponding
     lower-case letter.  If C is not an upper-case letter, C is
     returned unchanged.

 - Function: int toupper (int C)
     If C is a lower-case letter, `toupper' returns the corresponding
     upper-case letter.  Otherwise C is returned unchanged.

 - Function: int toascii (int C)
     This function converts C to a 7-bit `unsigned char' value that
     fits into the US/UK ASCII character set, by clearing the high-order
     bits.  This function is a BSD extension and is also an SVID
     extension.

 - Function: int _tolower (int C)
     This is identical to `tolower', and is provided for compatibility
     with the SVID.  *Note SVID::.

 - Function: int _toupper (int C)
     This is identical to `toupper', and is provided for compatibility
     with the SVID.


File: libc.info,  Node: Classification of Wide Characters,  Next: Using Wide Char Classes,  Prev: Case Conversion,  Up: Character Handling

Character class determination for wide characters
=================================================

   The second amendment to ISO C89 defines functions to classify wide
character.  Although the original ISO C89 standard already defined the
type `wchar_t' but no functions operating on them were defined.

   The general design of the classification functions for wide
characters is more general.  It allows to extend the set of available
classification beyond the set which is always available.  The POSIX
standard specifies a way how the extension can be done and this is
already implemented in the GNU C library implementation of the
`localedef' program.

   The character class functions are normally implemented using bitsets.
I.e., for the character in question the appropriate bitset is read from
a table and a test is performed whether a certain bit is set in this
bitset.  Which bit is tested for is determined by the class.

   For the wide character classification functions this is made visible.
There is a type representing the classification, a function to retrieve
this value for a specific class, and a function to test using the
classification value whether a given character is in this class.  On top
of this the normal character classification functions as used for
`char' objects can be defined.

 - Data type: wctype_t
     The `wctype_t' can hold a value which represents a character class.
     The ony defined way to generate such a value is by using the
     `wctype' function.

     This type is defined in `wctype.h'.

 - Function: wctype_t wctype (const char *PROPERTY)
     The `wctype' returns a value representing a class of wide
     characters which is identified by the string PROPERTY.  Beside
     some standard properties each locale can define its own ones.  In
     case no property with the given name is known for the current
     locale for the `LC_CTYPE' category the function returns zero.

     The properties known in every locale are:

     `"alnum"'         `"alpha"'         `"cntrl"'         `"digit"'         
     `"graph"'         `"lower"'         `"print"'         `"punct"'         
     `"space"'         `"upper"'         `"xdigit"'                          

     This function is declared in `wctype.h'.

   To test the membership of a character to one of the non-standard
classes the ISO C standard defines a completely new function.

 - Function: int iswctype (wint_t WC, wctype_t DESC)
     This function returns a nonzero value if WC is in the character
     class specified by DESC.  DESC must previously be returned by a
     successful call to `wctype'.

     This function is declared in `wctype.h'.

   The make it easier to use the commonly used classification functions
they are defined in the C library.  There is no need to use `wctype' is
the property string is one of the known character classes.  In some
situations it is desirable to construct the property string and then it
gets important that `wctype' can also handle the standard classes.

 - Function: int iswalnum (wint_t WC)
     This function returns a nonzero value if WC is an alphanumeric
     character (a letter or number); in other words, if either
     `iswalpha' or `iswdigit' is true of a character, then `iswalnum'
     is also true.

     This function can be implemented using

          iswctype (wc, wctype ("alnum"))

     It is declared in `wctype.h'.

 - Function: int iswalpha (wint_t WC)
     Returns true if WC is an alphabetic character (a letter).  If
     `iswlower' or `iswupper' is true of a character, then `iswalpha'
     is also true.

     In some locales, there may be additional characters for which
     `iswalpha' is true--letters which are neither upper case nor lower
     case.  But in the standard `"C"' locale, there are no such
     additional characters.

     This function can be implemented using

          iswctype (wc, wctype ("alpha"))

     It is declared in `wctype.h'.

 - Function: int iswcntrl (wint_t WC)
     Returns true if WC is a control character (that is, a character
     that is not a printing character).

     This function can be implemented using

          iswctype (wc, wctype ("cntrl"))

     It is declared in `wctype.h'.

 - Function: int iswdigit (wint_t WC)
     Returns true if WC is a digit (e.g., `0' through `9').  Please
     note that this function does not only return a nonzero value for
     *decimal* digits, but for all kinds of digits.  A consequence is
     that code like the following will *not* work unconditionally for
     wide characters:

          n = 0;
          while (iswctype (*wc))
            {
              n *= 10;
              n += *wc++ - L'0';
            }

     This function can be implemented using

          iswctype (wc, wctype ("digit"))

     It is declared in `wctype.h'.

 - Function: int iswgraph (wint_t WC)
     Returns true if WC is a graphic character; that is, a character
     that has a glyph associated with it.  The whitespace characters
     are not considered graphic.

     This function can be implemented using

          iswctype (wc, wctype ("graph"))

     It is declared in `wctype.h'.

 - Function: int iswlower (wint_t WC)
     Returns true if WC is a lower-case letter.  The letter need not be
     from the Latin alphabet, any alphabet representable is valid.

     This function can be implemented using

          iswctype (wc, wctype ("lower"))

     It is declared in `wctype.h'.

 - Function: int iswprint (wint_t WC)
     Returns true if WC is a printing character.  Printing characters
     include all the graphic characters, plus the space (` ') character.

     This function can be implemented using

          iswctype (wc, wctype ("print"))

     It is declared in `wctype.h'.

 - Function: int iswpunct (wint_t WC)
     Returns true if WC is a punctuation character.  This means any
     printing character that is not alphanumeric or a space character.

     This function can be implemented using

          iswctype (wc, wctype ("punct"))

     It is declared in `wctype.h'.

 - Function: int iswspace (wint_t WC)
     Returns true if WC is a "whitespace" character.  In the standard
     `"C"' locale, `iswspace' returns true for only the standard
     whitespace characters:

    `L' ''
          space

    `L'\f''
          formfeed

    `L'\n''
          newline

    `L'\r''
          carriage return

    `L'\t''
          horizontal tab

    `L'\v''
          vertical tab

     This function can be implemented using

          iswctype (wc, wctype ("space"))

     It is declared in `wctype.h'.

 - Function: int iswupper (wint_t WC)
     Returns true if WC is an upper-case letter.  The letter need not be
     from the Latin alphabet, any alphabet representable is valid.

     This function can be implemented using

          iswctype (wc, wctype ("upper"))

     It is declared in `wctype.h'.

 - Function: int iswxdigit (wint_t WC)
     Returns true if WC is a hexadecimal digit.  Hexadecimal digits
     include the normal decimal digits `0' through `9' and the letters
     `A' through `F' and `a' through `f'.

     This function can be implemented using

          iswctype (wc, wctype ("xdigit"))

     It is declared in `wctype.h'.

   The GNu C library provides also a function which is not defined in
the ISO C standard but which is available as a version for single byte
characters as well.

 - Function: int iswblank (wint_t WC)
     Returns true if WC is a blank character; that is, a space or a tab.
     This function is a GNU extension.  It is declared in `wchar.h'.


File: libc.info,  Node: Using Wide Char Classes,  Next: Wide Character Case Conversion,  Prev: Classification of Wide Characters,  Up: Character Handling

Notes on using the wide character classes
=========================================

   The first note is probably nothing astonishing but still
occasionally a cause of problems.  The `iswXXX' functions can be
implemented using macros and in fact, the GNU C library does this.
They are still available as real functions but when the `wctype.h'
header is included the macros will be used.  This is nothing new
compared to the `char' type versions of these functions.

   The second notes covers something which is new.  It can be best
illustrated by a (real-world) example.  The first piece of code is an
excerpt from the original code.  It is truncated a bit but the intention
should be clear.

     int
     is_in_class (int c, const char *class)
     {
       if (strcmp (class, "alnum") == 0)
         return isalnum (c);
       if (strcmp (class, "alpha") == 0)
         return isalpha (c);
       if (strcmp (class, "cntrl") == 0)
         return iscntrl (c);
       ...
       return 0;
     }

   Now with the `wctype' and `iswctype' one could avoid the `if'
cascades.  But rewriting the code as follows is wrong:

     int
     is_in_class (int c, const char *class)
     {
       wctype_t desc = wctype (class);
       return desc ? iswctype ((wint_t) c, desc) : 0;
     }

   The problem is that it is not guarateed that the wide character
representation of a single-byte character can be found using casting.
In fact, usually this fails miserably.  The correct solution for this
problem is to write the code as follows:

     int
     is_in_class (int c, const char *class)
     {
       wctype_t desc = wctype (class);
       return desc ? iswctype (btowc (c), desc) : 0;
     }

   *Note Converting a Character::, for more information on `btowc'.
Please note that this change probably does not improve the performance
of the program a lot since the `wctype' function still has to make the
string comparisons.  But it gets really interesting if the
`is_in_class' function would be called more than once using the same
class name.  In this case the variable DESC could be computed once and
reused for all the calls.  Therefore the above form of the function is
probably not the final one.


File: libc.info,  Node: Wide Character Case Conversion,  Prev: Using Wide Char Classes,  Up: Character Handling

Mapping of wide characters.
===========================

   As for the classification functions the ISO C standard also
generalizes the mapping functions.  Instead of only allowing the two
standard mappings the locale can contain others.  Again, the
`localedef' program already supports generating such locale data files.

 - Data Type: wctrans_t
     This data type is defined as a scalar type which can hold a value
     representing the locale-dependent character mapping.  There is no
     way to construct such a value beside using the return value of the
     `wctrans' function.

     This type is defined in `wctype.h'.

 - Function: wctrans_t wctrans (const char *PROPERTY)
     The `wctrans' function has to be used to find out whether a named
     mapping is defined in the current locale selected for the
     `LC_CTYPE' category.  If the returned value is non-zero it can
     afterwards be used in calls to `towctrans'.  If the return value is
     zero no such mapping is known in the current locale.

     Beside locale-specific mappings there are two mappings which are
     guaranteed to be available in every locale:

     `"tolower"'                        `"toupper"'                        

     This function is declared in `wctype.h'.

 - Function: wint_t towctrans (wint_t WC, wctrans_t DESC)
     The `towctrans' function maps the input character WC according to
     the rules of the mapping for which DESC is an descriptor and
     returns the so found value.  The DESC value must be obtained by a
     successful call to `wctrans'.

     This function is declared in `wctype.h'.

   The ISO C standard also defines for the generally available mappings
convenient shortcuts so that it is not necesary to call `wctrans' for
them.

 - Function: wint_t towlower (wint_t WC)
     If WC is an upper-case letter, `towlower' returns the corresponding
     lower-case letter.  If WC is not an upper-case letter, WC is
     returned unchanged.

     `towlower' can be implemented using

          towctrans (wc, wctrans ("tolower"))

     This function is declared in `wctype.h'.

 - Function: wint_t towupper (wint_t WC)
     If WC is a lower-case letter, `towupper' returns the corresponding
     upper-case letter.  Otherwise WC is returned unchanged.

     `towupper' can be implemented using

          towctrans (wc, wctrans ("toupper"))

     This function is declared in `wctype.h'.

   The same warnings given in the last section for the use of the wide
character classiffication function applies here.  It is not possible to
simply cast a `char' type value to a `wint_t' and use it as an argument
for `towctrans' calls.


File: libc.info,  Node: String and Array Utilities,  Next: Character Set Handling,  Prev: Character Handling,  Up: Top

String and Array Utilities
**************************

   Operations on strings (or arrays of characters) are an important
part of many programs.  The GNU C library provides an extensive set of
string utility functions, including functions for copying,
concatenating, comparing, and searching strings.  Many of these
functions can also operate on arbitrary regions of storage; for
example, the `memcpy' function can be used to copy the contents of any
kind of array.

   It's fairly common for beginning C programmers to "reinvent the
wheel" by duplicating this functionality in their own code, but it pays
to become familiar with the library functions and to make use of them,
since this offers benefits in maintenance, efficiency, and portability.

   For instance, you could easily compare one string to another in two
lines of C code, but if you use the built-in `strcmp' function, you're
less likely to make a mistake.  And, since these library functions are
typically highly optimized, your program may run faster too.

* Menu:

* Representation of Strings::   Introduction to basic concepts.
* String/Array Conventions::    Whether to use a string function or an
				 arbitrary array function.
* String Length::               Determining the length of a string.
* Copying and Concatenation::   Functions to copy the contents of strings
				 and arrays.
* String/Array Comparison::     Functions for byte-wise and character-wise
				 comparison.
* Collation Functions::         Functions for collating strings.
* Search Functions::            Searching for a specific element or substring.
* Finding Tokens in a String::  Splitting a string into tokens by looking
				 for delimiters.
* Encode Binary Data::          Encoding and Decoding of Binary Data.
* Argz and Envz Vectors::       Null-separated string vectors.


File: libc.info,  Node: Representation of Strings,  Next: String/Array Conventions,  Up: String and Array Utilities

Representation of Strings
=========================

   This section is a quick summary of string concepts for beginning C
programmers.  It describes how character strings are represented in C
and some common pitfalls.  If you are already familiar with this
material, you can skip this section.

   A "string" is an array of `char' objects.  But string-valued
variables are usually declared to be pointers of type `char *'.  Such
variables do not include space for the text of a string; that has to be
stored somewhere else--in an array variable, a string constant, or
dynamically allocated memory (*note Memory Allocation::.).  It's up to
you to store the address of the chosen memory space into the pointer
variable.  Alternatively you can store a "null pointer" in the pointer
variable.  The null pointer does not point anywhere, so attempting to
reference the string it points to gets an error.

   By convention, a "null character", `'\0'', marks the end of a
string.  For example, in testing to see whether the `char *' variable P
points to a null character marking the end of a string, you can write
`!*P' or `*P == '\0''.

   A null character is quite different conceptually from a null pointer,
although both are represented by the integer `0'.

   "String literals" appear in C program source as strings of
characters between double-quote characters (`"').  In ISO C, string
literals can also be formed by "string concatenation": `"a" "b"' is the
same as `"ab"'.  Modification of string literals is not allowed by the
GNU C compiler, because literals are placed in read-only storage.

   Character arrays that are declared `const' cannot be modified
either.  It's generally good style to declare non-modifiable string
pointers to be of type `const char *', since this often allows the C
compiler to detect accidental modifications as well as providing some
amount of documentation about what your program intends to do with the
string.

   The amount of memory allocated for the character array may extend
past the null character that normally marks the end of the string.  In
this document, the term "allocated size" is always used to refer to the
total amount of memory allocated for the string, while the term
"length" refers to the number of characters up to (but not including)
the terminating null character.

   A notorious source of program bugs is trying to put more characters
in a string than fit in its allocated size.  When writing code that
extends strings or moves characters into a pre-allocated array, you
should be very careful to keep track of the length of the text and make
explicit checks for overflowing the array.  Many of the library
functions *do not* do this for you!  Remember also that you need to
allocate an extra byte to hold the null character that marks the end of
the string.


File: libc.info,  Node: String/Array Conventions,  Next: String Length,  Prev: Representation of Strings,  Up: String and Array Utilities

String and Array Conventions
============================

   This chapter describes both functions that work on arbitrary arrays
or blocks of memory, and functions that are specific to null-terminated
arrays of characters.

   Functions that operate on arbitrary blocks of memory have names
beginning with `mem' (such as `memcpy') and invariably take an argument
which specifies the size (in bytes) of the block of memory to operate
on.  The array arguments and return values for these functions have
type `void *', and as a matter of style, the elements of these arrays
are referred to as "bytes".  You can pass any kind of pointer to these
functions, and the `sizeof' operator is useful in computing the value
for the size argument.

   In contrast, functions that operate specifically on strings have
names beginning with `str' (such as `strcpy') and look for a null
character to terminate the string instead of requiring an explicit size
argument to be passed.  (Some of these functions accept a specified
maximum length, but they also check for premature termination with a
null character.)  The array arguments and return values for these
functions have type `char *', and the array elements are referred to as
"characters".

   In many cases, there are both `mem' and `str' versions of a
function.  The one that is more appropriate to use depends on the exact
situation.  When your program is manipulating arbitrary arrays or
blocks of storage, then you should always use the `mem' functions.  On
the other hand, when you are manipulating null-terminated strings it is
usually more convenient to use the `str' functions, unless you already
know the length of the string in advance.


File: libc.info,  Node: String Length,  Next: Copying and Concatenation,  Prev: String/Array Conventions,  Up: String and Array Utilities

String Length
=============

   You can get the length of a string using the `strlen' function.
This function is declared in the header file `string.h'.

 - Function: size_t strlen (const char *S)
     The `strlen' function returns the length of the null-terminated
     string S.  (In other words, it returns the offset of the
     terminating null character within the array.)

     For example,
          strlen ("hello, world")
              => 12

     When applied to a character array, the `strlen' function returns
     the length of the string stored there, not its allocated size.
     You can get the allocated size of the character array that holds a
     string using the `sizeof' operator:

          char string[32] = "hello, world";
          sizeof (string)
              => 32
          strlen (string)
              => 12

     But beware, this will not work unless STRING is the character
     array itself, not a pointer to it.  For example:

          char string[32] = "hello, world";
          char *ptr = string;
          sizeof (string)
              => 32
          sizeof (ptr)
              => 4  /* (on a machine with 4 byte pointers) */

     This is an easy mistake to make when you are working with
     functions that take string arguments; those arguments are always
     pointers, not arrays.


 - Function: size_t strnlen (const char *S, size_t MAXLEN)
     The `strnlen' function returns the length of the null-terminated
     string S is this length is smaller than MAXLEN.  Otherwise it
     returns MAXLEN.  Therefore this function is equivalent to `(strlen
     (S) < n ? strlen (S) : MAXLEN)' but it is more efficient.

          char string[32] = "hello, world";
          strnlen (string, 32)
              => 12
          strnlen (string, 5)
              => 5

     This function is a GNU extension.


File: libc.info,  Node: Copying and Concatenation,  Next: String/Array Comparison,  Prev: String Length,  Up: String and Array Utilities

Copying and Concatenation
=========================

   You can use the functions described in this section to copy the
contents of strings and arrays, or to append the contents of one string
to another.  These functions are declared in the header file `string.h'.

   A helpful way to remember the ordering of the arguments to the
functions in this section is that it corresponds to an assignment
expression, with the destination array specified to the left of the
source array.  All of these functions return the address of the
destination array.

   Most of these functions do not work properly if the source and
destination arrays overlap.  For example, if the beginning of the
destination array overlaps the end of the source array, the original
contents of that part of the source array may get overwritten before it
is copied.  Even worse, in the case of the string functions, the null
character marking the end of the string may be lost, and the copy
function might get stuck in a loop trashing all the memory allocated to
your program.

   All functions that have problems copying between overlapping arrays
are explicitly identified in this manual.  In addition to functions in
this section, there are a few others like `sprintf' (*note Formatted
Output Functions::.) and `scanf' (*note Formatted Input Functions::.).

 - Function: void * memcpy (void *TO, const void *FROM, size_t SIZE)
     The `memcpy' function copies SIZE bytes from the object beginning
     at FROM into the object beginning at TO.  The behavior of this
     function is undefined if the two arrays TO and FROM overlap; use
     `memmove' instead if overlapping is possible.

     The value returned by `memcpy' is the value of TO.

     Here is an example of how you might use `memcpy' to copy the
     contents of an array:

          struct foo *oldarray, *newarray;
          int arraysize;
          ...
          memcpy (new, old, arraysize * sizeof (struct foo));

 - Function: void * mempcpy (void *TO, const void *FROM, size_t SIZE)
     The `mempcpy' function is nearly identical to the `memcpy'
     function.  It copies SIZE bytes from the object beginning at
     `from' into the object pointed to by TO.  But instead of returning
     the value of `to' it returns a pointer to the byte following the
     last written byte in the object beginning at TO.  I.e., the value
     is `((void *) ((char *) TO + SIZE))'.

     This function is useful in situations where a number of objects
     shall be copied to consecutive memory positions.

          void *
          combine (void *o1, size_t s1, void *o2, size_t s2)
          {
            void *result = malloc (s1 + s2);
            if (result != NULL)
              mempcpy (mempcpy (result, o1, s1), o2, s2);
            return result;
          }

     This function is a GNU extension.

 - Function: void * memmove (void *TO, const void *FROM, size_t SIZE)
     `memmove' copies the SIZE bytes at FROM into the SIZE bytes at TO,
     even if those two blocks of space overlap.  In the case of
     overlap, `memmove' is careful to copy the original values of the
     bytes in the block at FROM, including those bytes which also
     belong to the block at TO.

 - Function: void * memccpy (void *TO, const void *FROM, int C, size_t
          SIZE)
     This function copies no more than SIZE bytes from FROM to TO,
     stopping if a byte matching C is found.  The return value is a
     pointer into TO one byte past where C was copied, or a null
     pointer if no byte matching C appeared in the first SIZE bytes of
     FROM.

 - Function: void * memset (void *BLOCK, int C, size_t SIZE)
     This function copies the value of C (converted to an `unsigned
     char') into each of the first SIZE bytes of the object beginning
     at BLOCK.  It returns the value of BLOCK.

 - Function: char * strcpy (char *TO, const char *FROM)
     This copies characters from the string FROM (up to and including
     the terminating null character) into the string TO.  Like
     `memcpy', this function has undefined results if the strings
     overlap.  The return value is the value of TO.

 - Function: char * strncpy (char *TO, const char *FROM, size_t SIZE)
     This function is similar to `strcpy' but always copies exactly
     SIZE characters into TO.

     If the length of FROM is more than SIZE, then `strncpy' copies
     just the first SIZE characters.  Note that in this case there is
     no null terminator written into TO.

     If the length of FROM is less than SIZE, then `strncpy' copies all
     of FROM, followed by enough null characters to add up to SIZE
     characters in all.  This behavior is rarely useful, but it is
     specified by the ISO C standard.

     The behavior of `strncpy' is undefined if the strings overlap.

     Using `strncpy' as opposed to `strcpy' is a way to avoid bugs
     relating to writing past the end of the allocated space for TO.
     However, it can also make your program much slower in one common
     case: copying a string which is probably small into a potentially
     large buffer.  In this case, SIZE may be large, and when it is,
     `strncpy' will waste a considerable amount of time copying null
     characters.

 - Function: char * strdup (const char *S)
     This function copies the null-terminated string S into a newly
     allocated string.  The string is allocated using `malloc'; see
     *Note Unconstrained Allocation::.  If `malloc' cannot allocate
     space for the new string, `strdup' returns a null pointer.
     Otherwise it returns a pointer to the new string.

 - Function: char * strndup (const char *S, size_t SIZE)
     This function is similar to `strdup' but always copies at most
     SIZE characters into the newly allocated string.

     If the length of S is more than SIZE, then `strndup' copies just
     the first SIZE characters and adds a closing null terminator.
     Otherwise all characters are copied and the string is terminated.

     This function is different to `strncpy' in that it always
     terminates the destination string.

 - Function: char * stpcpy (char *TO, const char *FROM)
     This function is like `strcpy', except that it returns a pointer to
     the end of the string TO (that is, the address of the terminating
     null character) rather than the beginning.

     For example, this program uses `stpcpy' to concatenate `foo' and
     `bar' to produce `foobar', which it then prints.

          #include <string.h>
          #include <stdio.h>
          
          int
          main (void)
          {
            char buffer[10];
            char *to = buffer;
            to = stpcpy (to, "foo");
            to = stpcpy (to, "bar");
            puts (buffer);
            return 0;
          }

     This function is not part of the ISO or POSIX standards, and is not
     customary on Unix systems, but we did not invent it either.
     Perhaps it comes from MS-DOG.

     Its behavior is undefined if the strings overlap.

 - Function: char * stpncpy (char *TO, const char *FROM, size_t SIZE)
     This function is similar to `stpcpy' but copies always exactly
     SIZE characters into TO.

     If the length of FROM is more then SIZE, then `stpncpy' copies
     just the first SIZE characters and returns a pointer to the
     character directly following the one which was copied last.  Note
     that in this case there is no null terminator written into TO.

     If the length of FROM is less than SIZE, then `stpncpy' copies all
     of FROM, followed by enough null characters to add up to SIZE
     characters in all.  This behaviour is rarely useful, but it is
     implemented to be useful in contexts where this behaviour of the
     `strncpy' is used.  `stpncpy' returns a pointer to the *first*
     written null character.

     This function is not part of ISO or POSIX but was found useful
     while developing the GNU C Library itself.

     Its behaviour is undefined if the strings overlap.

 - Macro: char * strdupa (const char *S)
     This function is similar to `strdup' but allocates the new string
     using `alloca' instead of `malloc' (*note Variable Size
     Automatic::.).  This means of course the returned string has the
     same limitations as any block of memory allocated using `alloca'.

     For obvious reasons `strdupa' is implemented only as a macro; you
     cannot get the address of this function.  Despite this limitation
     it is a useful function.  The following code shows a situation
     where using `malloc' would be a lot more expensive.

          #include <paths.h>
          #include <string.h>
          #include <stdio.h>
          
          const char path[] = _PATH_STDPATH;
          
          int
          main (void)
          {
            char *wr_path = strdupa (path);
            char *cp = strtok (wr_path, ":");
          
            while (cp != NULL)
              {
                puts (cp);
                cp = strtok (NULL, ":");
              }
            return 0;
          }

     Please note that calling `strtok' using PATH directly is invalid.

     This function is only available if GNU CC is used.

 - Macro: char * strndupa (const char *S, size_t SIZE)
     This function is similar to `strndup' but like `strdupa' it
     allocates the new string using `alloca' *note Variable Size
     Automatic::..  The same advantages and limitations of `strdupa'
     are valid for `strndupa', too.

     This function is implemented only as a macro, just like `strdupa'.

     `strndupa' is only available if GNU CC is used.

 - Function: char * strcat (char *TO, const char *FROM)
     The `strcat' function is similar to `strcpy', except that the
     characters from FROM are concatenated or appended to the end of
     TO, instead of overwriting it.  That is, the first character from
     FROM overwrites the null character marking the end of TO.

     An equivalent definition for `strcat' would be:

          char *
          strcat (char *to, const char *from)
          {
            strcpy (to + strlen (to), from);
            return to;
          }

     This function has undefined results if the strings overlap.

   Programmers using the `strcat' function (or the following `strncat'
function for that matter) can easily be recognize as lazy.  In almost
all situations the lengths of the participating strings are known.  Or
at least, one could know them if one keeps track of the results of the
various function calls.  But then it is very inefficient to use
`strcat'.  A lot of time is wasted finding the end of the destination
string so that the actual copying can start.  This is a common example:

     /* This function concats arbitrary many strings.  The last
        parameter must be `NULL'.  */
     char *
     concat (const char *str, ...)
     {
       va_list ap, ap2;
       size_t total = 1;
       const char *s;
       char *result;
     
       va_start (ap, str);
       /* Actually `va_copy', but this is the name more gcc versions
          understand.  */
       __va_copy (ap2, ap);
     
       /* Determine how much space we need.  */
       for (s = str; s != NULL; s = va_arg (ap, const char *))
         total += strlen (s);
     
       va_end (ap);
     
       result = (char *) malloc (total);
       if (result != NULL)
         {
           result[0] = '\0';
     
           /* Copy the strings.  */
           for (s = str; s != NULL; s = va_arg (ap2, const char *))
             strcat (result, s);
         }
     
       va_end (ap2);
     
       return result;
     }

   This looks quite simple, especially the second loop where the strings
are actually copied.  But these innocent lines hide a major performance
penalty.  Just imagine that ten strings of 100 bytes each have to be
concatenated.  For the second string we search the already stored 100
bytes for the end of the string so that we can append the next string.
For all strings in total the comparisons necessary to find the end of
the intermediate results sums up to 5500!  If we combine the copying
with the search for the allocation we can write this function more
efficent:

     char *
     concat (const char *str, ...)
     {
       va_list ap;
       size_t allocated = 100;
       char *result = (char *) malloc (allocated);
       char *wp;
     
       if (allocated != NULL)
         {
           char *newp;
     
           va_start (ap, atr);
     
           wp = result;
           for (s = str; s != NULL; s = va_arg (ap, const char *))
             {
               size_t len = strlen (s);
     
               /* Resize the allocated memory if necessary.  */
               if (wp + len + 1 > result + allocated)
                 {
                   allocated = (allocated + len) * 2;
                   newp = (char *) realloc (result, allocated);
                   if (newp == NULL)
                     {
                       free (result);
                       return NULL;
                     }
                   wp = newp + (wp - result);
                   result = newp;
                 }
     
               wp = mempcpy (wp, s, len);
             }
     
           /* Terminate the result string.  */
           *wp++ = '\0';
     
           /* Resize memory to the optimal size.  */
           newp = realloc (result, wp - result);
           if (newp != NULL)
             result = newp;
     
           va_end (ap);
         }
     
       return result;
     }

   With a bit more knowledge about the input strings one could fine-tune
the memory allocation.  The difference we are pointing to here is that
we don't use `strcat' anymore.  We always keep track of the length of
the current intermediate result so we can safe us the search for the
end of the string and use `mempcpy'.  Please note that we also don't
use `stpcpy' which might seem more natural since we handle with
strings.  But this is not necessary since we already know the length of
the string and therefore can use the faster memory copying function.

   Whenever a programmer feels the need to use `strcat' she or he
should think twice and look through the program whether the code cannot
be rewritten to take advantage of already calculated results.  Again: it
is almost always unnecessary to use `strcat'.

 - Function: char * strncat (char *TO, const char *FROM, size_t SIZE)
     This function is like `strcat' except that not more than SIZE
     characters from FROM are appended to the end of TO.  A single null
     character is also always appended to TO, so the total allocated
     size of TO must be at least `SIZE + 1' bytes longer than its
     initial length.

     The `strncat' function could be implemented like this:

          char *
          strncat (char *to, const char *from, size_t size)
          {
            strncpy (to + strlen (to), from, size);
            return to;
          }

     The behavior of `strncat' is undefined if the strings overlap.

   Here is an example showing the use of `strncpy' and `strncat'.
Notice how, in the call to `strncat', the SIZE parameter is computed to
avoid overflowing the character array `buffer'.

     #include <string.h>
     #include <stdio.h>
     
     #define SIZE 10
     
     static char buffer[SIZE];
     
     main ()
     {
       strncpy (buffer, "hello", SIZE);
       puts (buffer);
       strncat (buffer, ", world", SIZE - strlen (buffer) - 1);
       puts (buffer);
     }

The output produced by this program looks like:

     hello
     hello, wo

 - Function: void bcopy (const void *FROM, void *TO, size_t SIZE)
     This is a partially obsolete alternative for `memmove', derived
     from BSD.  Note that it is not quite equivalent to `memmove',
     because the arguments are not in the same order and there is no
     return value.

 - Function: void bzero (void *BLOCK, size_t SIZE)
     This is a partially obsolete alternative for `memset', derived from
     BSD.  Note that it is not as general as `memset', because the only
     value it can store is zero.

