From Wikipedia, the free encyclopedia
  (Redirected from C string)
Jump to navigationJump to search

The C programming language has a set of functions implementing operations on strings (character strings and byte strings) in its standard library. Various operations, such as copying, concatenation, tokenization and searching are supported. For character strings, the standard library uses the convention that strings are null-terminated: a string of n characters is represented as an array of n + 1 elements, the last of which is a "NUL" character.

The only support for strings in the programming language proper is that the compiler translates quoted string constants into null-terminated strings.

Definitions[edit]

A string is defined as a contiguous sequence of code units terminated by the first zero code unit (often called the NUL code unit).[1] This means a string cannot contain the zero code unit, as the first one seen marks the end of the string. The length of a string is the number of code units before the zero code unit.[1] The memory occupied by a string is always one more code unit than the length, as space is needed to store the zero terminator.

Generally, the term string means a string where the code unit is of type char, which is exactly 8 bits on all modern machines. C90 defines wide strings[1] which use a code unit of type wchar_t, which is 16 or 32 bits on modern machines. This was intended for Unicode but it is increasingly common to use UTF-8 in normal strings for Unicode instead.

Strings are passed to functions by passing a pointer to the first code unit. Since char* and wchar_t* are different types, the functions that process wide strings are different than the ones processing normal strings and have different names.

String literals ("text" in the C source code) are converted to arrays during compilation.[2] The result is an array of code units containing all the characters plus a trailing zero code unit. In C90 L"text" produces a wide string. A string literal can contain the zero code unit (one way is to put \0 into the source), but this will cause the string to end at that point. The rest of the literal will be placed in memory (with another zero code unit added to the end) but it is impossible to know those code units were translated from the string literal, therefore such source code is not a string literal.[3]

Character encodings[edit]

Each string ends at the first occurrence of the zero code unit of the appropriate kind (char or wchar_t). Consequently, a byte string (char*) can contain non-NUL characters in ASCII or any ASCII extension, but not characters in encodings such as UTF-16 (even though a 16-bit code unit might be nonzero, its high or low byte might be zero). The encodings that can be stored in wide strings are defined by the width of wchar_t. In most implementations, wchar_t is at least 16 bits, and so all 16-bit encodings, such as UCS-2, can be stored. If wchar_t is 32-bits, then 32-bit encodings, such as UTF-32, can be stored. (The standard requires a "type that holds any wide character", which on Windows no longer holds true since the UCS-2 to UTF-16 shift.) C++11 and C11 add two types with explicit widths char16_t and char32_t.[4]

Variable-width encodings can be used in both byte strings and wide strings. String length and offsets are measured in bytes or wchar_t, not in "characters", which can be confusing to beginning programmers. UTF-8 and Shift JIS are often used in C byte strings, while UTF-16 is often used in C wide strings when wchar_t is 16 bits. Truncating strings with variable length characters using functions like strncpy can produce invalid sequences at the end of the string. This can be unsafe if the truncated parts are interpreted by code that assumes the input is valid.

Support for Unicode literals such as char foo[512] = "φωωβαρ";(UTF-8) or wchar_t foo[512] = L"φωωβαρ"; (UTF-16 or UTF-32, depends on wchar_t) is implementation defined,[5] and may require that the source code be in the same encoding, especially for char where compilers might just copy whatever is between the quotes. Some compilers or editors will require entering all non-ASCII characters as \xNN sequences for each byte of UTF-8, and/or \uNNNN for each word of UTF-16. Since C11 (and C++11), a new char foo[512] = u8"φωωβαρ"; literal syntax is available that guarantees UTF-8 for a bytestring literal.[6]

Overview of functions[edit]

Most of the functions that operate on C strings are declared in the string.h header (cstring in C++), while functions that operate on C wide strings are declared in the wchar.h header (cwchar in C++). These headers also contain declarations of functions used for handling memory buffers; the name is thus something of a misnomer.

Functions declared in string.h are extremely popular since, as a part of the C standard library, they are guaranteed to work on any platform which supports C. However, some security issues exist with these functions, such as potential buffer overflows when not used carefully and properly, causing the programmers to prefer safer and possibly less portable variants, out of which some popular ones are listed below. Some of these functions also violate const-correctness by accepting a const string pointer and returning a non-const pointer within the string. To correct this, some have been separated into two overloaded functions in the C++ version of the standard library.

In historical documentation the term "character" was often used instead of "byte" for C strings, which leads many[who?] to believe that these functions somehow do not work for UTF-8. In fact all lengths are defined as being in bytes and this is true in all implementations, and these functions work as well with UTF-8 as with single-byte encodings. The BSD documentation has been fixed to make this clear, but POSIX, Linux, and Windows documentation still uses "character" in many places where "byte" or "wchar_t" is the correct term.

Functions for handling memory buffers can process sequences of bytes that include null-byte as part of the data. Names of these functions typically start with mem, as opposite to the str prefix.

Constants and types[edit]

Functions[edit]

Multibyte functions[edit]

These functions all take a pointer to a mbstate_t object that the caller must maintain. This was originally intended to track shift states in the mb encodings, but modern ones such as UTF-8 do not need this. However these functions were designed on the assumption that the wc encoding is not a variable-width encoding and thus are designed to deal with exactly one wchar_t at a time, passing it by value rather than using a string pointer. As UTF-16 is a variable-width encoding, the mbstate_t has been reused to keep track of surrogate pairs in the wide encoding, though the caller must still detect and call mbtowc twice for a single character.[65][66][67]

Numeric conversions[edit]

The C standard library contains several functions for numeric conversions. The functions that deal with byte strings are defined in the stdlib.h header (cstdlib header in C++). The functions that deal with wide strings are defined in the wchar.h header (cwchar header in C++).

The strtoxxx functions are not const-correct, since they accept a const string pointer and return a non-const pointer within the string.

Also, since the Normative Amendment 1 (C95), atoxx functions are considered subsumed by strtoxxx functions, for which reason neither C95 nor any later standard provides wide-character versions of these functions. The argument against atoxx is that they do not differentiate between an error and a 0.[80]

Popular extensions[edit]

Replacements[edit]

Despite the well-established need to replace strcat[13] and strcpy[9] with functions that do not allow buffer overflows, no accepted standard has arisen. This is partly due to the mistaken belief by many C programmers that strncat and strncpy have the desired behavior; however, neither function was designed for this (they were intended to manipulate null-padded fixed-size string buffers, a data format less commonly used in modern software), and the behavior and arguments are non-intuitive and often written incorrectly even by expert programmers.[91]

The most popular[a] replacement are the strlcat and strlcpy functions, which appeared in OpenBSD 2.4 in December, 1998.[91] These functions always write one NUL to the destination buffer, truncating the result if necessary, and return the size of buffer that would be needed, which allows detection of the truncation and provides a size for creating a new buffer that will not truncate. They have been criticized on the basis of allegedly being inefficient,[94] encouraging the use of C strings (instead of some superior alternative form of string),[95][96] and hiding other potential errors.[97][98] Consequently, they have not been included in the GNU C library (used by software on Linux), although they are implemented in the C libraries for OpenBSD, FreeBSD, NetBSD, Solaris, OS X, and QNX, as well as in alternative C libraries for Linux, such as musl introduced in 2011.[99][100] The lack of GNU C library support has not stopped various software authors from using it and bundling a replacement, among other SDL, GLib, ffmpeg, rsync, and even internally in the Linux kernel. Open source implementations for these functions are available.[101][102]

Sometimes memcpy[44] or memmove[46] are used, as they may be more efficient than strcpy as they do not repeatedly check for NUL (this is less true on modern processors). Since they need a buffer length as a parameter, correct setting of this parameter can avoid buffer overflows.

As part of its 2004 Security Development Lifecycle, Microsoft introduced a family of "secure" functions including strcpy_s and strcat_s (along with many others).[103] These functions were standardized with some minor changes as part of the optional C11 (Annex K) proposed by ISO/IEC WDTR 24731. These functions perform various checks including whether the string is too long to fit in the buffer. If the checks fail, a user-specified "runtime-constraint handler" function is called,[104] which usually aborts the program.[105][106] Some functions perform destructive operations before calling the runtime-constraint handler; for example, strcat_s sets the destination to the empty string,[107] which can make it difficult to recover from error conditions or debug them. These functions attracted considerable criticism because initially they were implemented only on Windows and at the same time warning messages started to be produced by Microsoft Visual C++ suggesting the programmers to use these functions instead of standard ones. This has been speculated by some to be an attempt by Microsoft to lock developers into its platform.[108] Although open-source implementations of these functions are available, these functions are not present in common Unix C libraries.[109] Experience with these functions has shown significant problems with their adoption and errors in usage, so the removal of Annex K is proposed for the next revision of the C standard.[110] Usage of memset_s has also been suggested as a way to avoid unwanted compiler optimizations.[111][112]

See also[edit]

  • C syntax § Strings – source code syntax, including backslash escape sequences
  • String functions

Notes[edit]

  1. ^ On GitHub, there are 7,813,206 uses of strlcpy, versus 38,644 uses of strcpy_s (and 15,286,150 uses of strcpy).[citation needed]

References[edit]

  1. ^ a b c "The C99 standard draft + TC3" (PDF). §7.1.1p1. Retrieved 7 January 2011.CS1 maint: location (link)
  2. ^ "The C99 standard draft + TC3" (PDF). §6.4.5p7. Retrieved 7 January 2011.CS1 maint: location (link)
  3. ^ "The C99 standard draft + TC3" (PDF). Section 6.4.5 footnote 66. Retrieved 7 January 2011.CS1 maint: location (link)
  4. ^ "Fundamental types". en.cppreference.com.
  5. ^ "The C99 standard draft + TC3" (PDF). §5.1.1.2 Translation phases, p1. Retrieved 23 December 2011.CS1 maint: location (link)
  6. ^ "string literals". en.cppreference.com. Retrieved 23 December 2019.
  7. ^ "stddef.h - standard type definitions". The Open Group. Retrieved 28 January 2017.
  8. ^ Gillam, Richard (2003). Unicode Demystified: A Practical Programmer's Guide to the Encoding Standard. Addison-Wesley Professional. p. 714. ISBN 9780201700527.
  9. ^ a b "strcpy - cppreference.com". En.cppreference.com. 2 January 2014. Retrieved 6 March 2014.
  10. ^ "wcscpy - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  11. ^ "strncpy - cppreference.com". En.cppreference.com. 4 October 2013. Retrieved 6 March 2014.
  12. ^ "wcsncpy - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  13. ^ a b "strcat - cppreference.com". En.cppreference.com. 8 October 2013. Retrieved 6 March 2014.
  14. ^ "wcscat - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  15. ^ "strncat - cppreference.com". En.cppreference.com. 1 July 2013. Retrieved 6 March 2014.
  16. ^ "wcsncat - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  17. ^ "strxfrm - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  18. ^ "wcsxfrm - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  19. ^ "strlen - cppreference.com". En.cppreference.com. 27 December 2013. Retrieved 6 March 2014.
  20. ^ "wcslen - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  21. ^ "strcmp - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  22. ^ "wcscmp - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  23. ^ "strncmp - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  24. ^ "wcsncmp - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  25. ^ "strcoll - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  26. ^ "wcscoll - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  27. ^ "strchr - cppreference.com". En.cppreference.com. 23 February 2014. Retrieved 6 March 2014.
  28. ^ "wcschr - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  29. ^ "strrchr - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  30. ^ "wcsrchr - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  31. ^ "strspn - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  32. ^ "wcsspn - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  33. ^ "strcspn - cppreference.com". En.cppreference.com. 31 May 2013. Retrieved 6 March 2014.
  34. ^ "wcscspn - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  35. ^ "strpbrk - cppreference.com". En.cppreference.com. 31 May 2013. Retrieved 6 March 2014.
  36. ^ "wcspbrk - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  37. ^ "strstr - cppreference.com". En.cppreference.com. 16 October 2013. Retrieved 6 March 2014.
  38. ^ "wcsstr - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  39. ^ "strtok - cppreference.com". En.cppreference.com. 3 September 2013. Retrieved 6 March 2014.
  40. ^ "wcstok - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  41. ^ "strerror - cppreference.com". En.cppreference.com. 31 May 2013. Retrieved 6 March 2014.
  42. ^ "memset - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  43. ^ "wmemset - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  44. ^ a b "memcpy - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  45. ^ "wmemcpy - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  46. ^ a b "memmove - cppreference.com". En.cppreference.com. 25 January 2014. Retrieved 6 March 2014.
  47. ^ "wmemmove - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  48. ^ "memcmp - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  49. ^ "wmemcmp - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  50. ^ "memchr - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  51. ^ "wmemchr - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  52. ^ "mblen - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  53. ^ "mbtowc - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  54. ^ "wctomb - cppreference.com". En.cppreference.com. 4 February 2014. Retrieved 6 March 2014.
  55. ^ "mbstowcs - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  56. ^ "wcstombs - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  57. ^ "btowc - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  58. ^ "wctob - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  59. ^ "mbsinit - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  60. ^ "mbrlen - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  61. ^ "mbrtowc - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  62. ^ "wcrtomb - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  63. ^ "mbsrtowcs - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  64. ^ "wcsrtombs - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  65. ^ "6.3.2 Representing the state of the conversion". The GNU C Library. Retrieved 31 January 2017.
  66. ^ "root/src/multibyte/c16rtomb.c". Retrieved 31 January 2017.
  67. ^ "Contents of /stable/11/lib/libc/locale/c16rtomb.c". Retrieved 31 January 2017.
  68. ^ "atof - cppreference.com". En.cppreference.com. 31 May 2013. Retrieved 6 March 2014.
  69. ^ "atoi, atol, atoll - cppreference.com". En.cppreference.com. 18 January 2014. Retrieved 6 March 2014.
  70. ^ "strtof, strtod, strtold - cppreference.com". En.cppreference.com. 4 February 2014. Retrieved 6 March 2014.
  71. ^ "strtof, strtod, strtold - cppreference.com". En.cppreference.com. 4 February 2014. Retrieved 6 March 2014.
  72. ^ "strtof, strtod, strtold - cppreference.com". En.cppreference.com. 4 February 2014. Retrieved 6 March 2014.
  73. ^ "wcstof, wcstod, wcstold - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  74. ^ "wcstof, wcstod, wcstold - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  75. ^ "wcstof, wcstod, wcstold - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  76. ^ "strtol, strtoll - cppreference.com". En.cppreference.com. 4 February 2014. Retrieved 6 March 2014.
  77. ^ "wcstol, wcstoll - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  78. ^ "strtoul, strtoull - cppreference.com". En.cppreference.com. 4 February 2014. Retrieved 6 March 2014.
  79. ^ "wcstoul, wcstoull - cppreference.com". En.cppreference.com. Retrieved 6 March 2014.
  80. ^ C99 Rationale, 7.20.1.1
  81. ^ "bzero". The Open Group. Retrieved 27 November 2017.
  82. ^ "bzero(3)". OpenBSD. Retrieved 27 November 2017.
  83. ^ "memccpy". Pubs.opengroup.org. Retrieved 6 March 2014.
  84. ^ "mempcpy(3) - Linux manual page". Kernel.org. Retrieved 6 March 2014.
  85. ^ "strcasecmp(3) - Linux manual page". Kernel.org. Retrieved 6 March 2014.
  86. ^ a b "strcat_s, wcscat_s, _mbscat_s". Msdn.microsoft.com. Retrieved 6 March 2014.
  87. ^ "strdup". Pubs.opengroup.org. Retrieved 6 March 2014.
  88. ^ "strerror(3) - Linux manual page". man7.org. Retrieved 3 November 2019.
  89. ^ "String | stricmp()". C Programming Expert.com. Retrieved 6 March 2014.
  90. ^ a b "strlcpy, strlcat — size-bounded string copying and concatenation". OpenBSD. Retrieved 26 May 2016.
  91. ^ a b c d Todd C. Miller; Theo de Raadt (1999). "strlcpy and strlcat – consistent, safe, string copy and concatenation". USENIX '99.
  92. ^ "strsignal". Pubs.opengroup.org. Retrieved 6 March 2014.
  93. ^ "strtok". Pubs.opengroup.org. Retrieved 6 March 2014.
  94. ^ Miller, Damien (October 2005). "Secure Portability" (PDF). Retrieved 26 June 2016. This [strlcpy and strlcat] API has been adopted by most modern operating systems and many standalone software packages [...]. The notable exception is the GNU standard C library, glibc, whose maintainer steadfastly refuses to include these improved APIs, labelling them "horribly inefficient BSD crap", despite prior evidence that they are faster is most cases than the APIs they replace.
  95. ^ libc-alpha mailing list, selected messages from 8 August 2000 thread: 53, 60, 61
  96. ^ The ups and downs of strlcpy(); LWN.net
  97. ^ "Adding strlcpy() to glibc". lwn.net. Correct string handling means that you always know how long your strings are and therefore you can you memcpy (instead of strcpy).
  98. ^ strlcpy(3) – Linux Library Functions Manual "However, one may question the validity of such optimizations, as they defeat the whole purpose of strlcpy() and strlcat(). As a matter of fact, the first version of this manual page got it wrong."
  99. ^ "root/src/string/strlcpy.c". Retrieved 28 January 2017.
  100. ^ "root/src/string/strlcat.c". Retrieved 28 January 2017.
  101. ^ Todd C. Miller. "strlcpy.c". BSD Cross Reference.
  102. ^ Todd C. Miller. "strlcat.c". BSD Cross Reference.
  103. ^ Lovell, Martyn. "Repel Attacks on Your Code with the Visual Studio 2005 Safe C and C++ Libraries". Retrieved 13 February 2015.
  104. ^ "The C11 standard draft" (PDF). §K.3.1.4p2. Retrieved 13 February 2013.CS1 maint: location (link)
  105. ^ "The C11 standard draft" (PDF). §K.3.6.1.1p4. Retrieved 13 February 2013.CS1 maint: location (link)
  106. ^ "Parameter Validation".
  107. ^ "The C11 standard draft" (PDF). §K.3.7.2.1p4. Retrieved 13 February 2013.CS1 maint: location (link)
  108. ^ Danny Kalev. "They're at it again". InformIT. Archived from the original on 15 January 2012. Retrieved 10 November 2011.
  109. ^ Safe C Library. "The Safe C Library provides bound checking memory and string functions per ISO/IEC TR24731". Sourceforge. Retrieved 6 March 2013.
  110. ^ "Field Experience With Annex K — Bounds Checking Interfaces". Retrieved 5 November 2015.
  111. ^ "MSC06-C. Beware of compiler optimizations". SEI CERT C Coding Standard.
  112. ^ memset_s(3) – FreeBSD Library Functions Manual

External links[edit]

  • Fast memcpy in C, multiple C coding examples to target different types of CPU instruction architectures