The
C programming language has a set of functions implementing operations on
strings
String or strings may refer to:
*String (structure), a long flexible structure made from threads twisted together, which is used to tie, bind, or hang other objects
Arts, entertainment, and media Films
* ''Strings'' (1991 film), a Canadian anim ...
(character strings and byte strings) in its
standard library
In computer programming, a standard library is the library made available across implementations of a programming language. These libraries are conventionally described in programming language specifications; however, contents of a language's as ...
. Various operations, such as copying,
concatenation
In formal language, formal language theory and computer programming, string concatenation is the operation of joining character string (computer science), character strings wikt:end-to-end, end-to-end. For example, the concatenation of "sno ...
,
tokenization
Tokenization may refer to:
* Tokenization (lexical analysis) in language processing
* Tokenization (data security) in the field of data security
* Word segmentation
* Tokenism
Tokenism is the practice of making only a perfunctory or symbolic ...
and searching are supported. For character strings, the standard library uses the convention that strings are
null-terminated: a string of characters is represented as an
array
An array is a systematic arrangement of similar objects, usually in rows and columns.
Things called an array include:
{{TOC right
Music
* In twelve-tone and serial composition, the presentation of simultaneous twelve-tone sets such that the ...
of elements, the last of which is a character (with numeric value 0).
The only support for strings in the programming language proper is that the compiler translates quoted
string constants into null-terminated strings.
Definitions
A string is defined as a contiguous sequence of
code unit
Character encoding is the process of assigning numbers to graphical characters, especially the written characters of human language, allowing them to be stored, transmitted, and transformed using digital computers. The numerical values that ...
s terminated by the first zero code unit (often called the ''NUL'' code unit).
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.
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''
which use a code unit of type
wchar_t
, which is 16 or 32 bits on modern machines. This was intended for
Unicode
Unicode, formally The Unicode Standard,The formal version reference is is an information technology Technical standard, standard for the consistent character encoding, encoding, representation, and handling of Character (computing), text expre ...
but it is increasingly common to use
UTF-8
UTF-8 is a variable-width encoding, variable-length character encoding used for electronic communication. Defined by the Unicode Standard, the name is derived from ''Unicode'' (or ''Universal Coded Character Set'') ''Transformation Format 8-bit'' ...
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 literal
A string literal (computer programming), literal or anonymous string is a String (computer science), string value in the source code of a computer program. Modern Computer programming, programming languages commonly use a quoted sequence of charact ...
s (
"text"
in the C source code) are converted to arrays during compilation. 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.
Character encodings
Each string ends at the first occurrence of the zero code unit of the appropriate kind (
char
or
wchar_t
). Consequently, a byte string () can contain non-
NUL characters in
ASCII
ASCII ( ), abbreviated from American Standard Code for Information Interchange, is a character encoding standard for electronic communication. ASCII codes represent text in computers, telecommunications equipment, and other devices. Because of ...
or any
ASCII extension
Extended ASCII is a repertoire of character encodings that include (most of) the original 96 ASCII character set, plus up to 128 additional characters. There is no formal definition of "extended ASCII", and even use of the term is sometimes critic ...
, but not characters in encodings such as
UTF-16
UTF-16 (16-bit computing, 16-bit Unicode Transformation Format) is a character encoding capable of encoding all 1,112,064 valid code points of Unicode (in fact this number of code points is dictated by the design of UTF-16). The encoding is variab ...
(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
The Universal Coded Character Set (UCS, Unicode) is a standard set of characters defined by the international standard ISO/IEC 10646, ''Information technology — Universal Coded Character Set (UCS)'' (plus amendments to that standard), whi ...
, can be stored. If
wchar_t
is 32-bits, then 32-bit encodings, such as
UTF-32
UTF-32 (32- bit Unicode Transformation Format) is a fixed-length encoding used to encode Unicode code points that uses exactly 32 bits (four bytes) per code point (but a number of leading bits must be zero as there are far fewer than 232 Unicode ...
, 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 and .
Variable-width encoding
A variable-width encoding is a type of character encoding scheme in which codes of differing lengths are used to encode a character set (a repertoire of symbols) for representation, usually in a computer. Most common variable-width encodings are ...
s 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
UTF-8 is a variable-width encoding, variable-length character encoding used for electronic communication. Defined by the Unicode Standard, the name is derived from ''Unicode'' (or ''Universal Coded Character Set'') ''Transformation Format 8-bit'' ...
and
Shift JIS
Shift JIS (Shift Japanese Industrial Standards, also SJIS, MIME name Shift_JIS, known as PCK in Solaris contexts) is a character encoding for the Japanese language, originally developed by a Japanese company called ASCII Corporation in conjunctio ...
are often used in C byte strings, while
UTF-16
UTF-16 (16-bit computing, 16-bit Unicode Transformation Format) is a character encoding capable of encoding all 1,112,064 valid code points of Unicode (in fact this number of code points is dictated by the design of UTF-16). The encoding is variab ...
is often used in C wide strings when
wchar_t
is 16 bits. Truncating strings with variable-width 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 (UTF-8) or (UTF-16 or UTF-32, depends on ) is implementation defined,
and may require that the source code be in the same encoding, especially for 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 literal syntax is available that guarantees UTF-8 for a bytestring literal.
Overview of functions
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
The C standard library or libc is the standard library for the C programming language, as specified in the ISO C standard.ISO/IEC (2018). '' ISO/IEC 9899:2018(E): Programming Languages - C §7'' Starting from the original ANSI C standard, it wa ...
, they are guaranteed to work on any platform which supports C. However, some security issues exist with these functions, such as potential
buffer overflow
In information security and programming, a buffer overflow, or buffer overrun, is an anomaly whereby a program, while writing data to a buffer, overruns the buffer's boundary and overwrites adjacent memory locations.
Buffers are areas of memory ...
s 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
In some programming languages, const is a type qualifier (a keyword applied to a data type) that indicates that the data is read-only. While this can be used to declare constants, in the C family of languages differs from similar constructs in ...
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 to believe that these functions somehow do not work for
UTF-8
UTF-8 is a variable-width encoding, variable-length character encoding used for electronic communication. Defined by the Unicode Standard, the name is derived from ''Unicode'' (or ''Universal Coded Character Set'') ''Transformation Format 8-bit'' ...
. 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
Functions
Multibyte functions
These functions all take a pointer to a object that the caller must maintain. This was originally intended to track shift states in the encodings, but modern ones such as UTF-8 do not need this. However these functions were designed on the assumption that the encoding is not a
variable-width encoding
A variable-width encoding is a type of character encoding scheme in which codes of differing lengths are used to encode a character set (a repertoire of symbols) for representation, usually in a computer. Most common variable-width encodings are ...
and thus are designed to deal with exactly one at a time, passing it by value rather than using a string pointer. As UTF-16 is a variable-width encoding, the has been reused to keep track of surrogate pairs in the wide encoding, though the caller must still detect and call twice for a single character.
Numeric conversions
The C standard library contains several functions for numeric conversions. The functions that deal with byte strings are defined in the header ( header in C++). The functions that deal with wide strings are defined in the header ( header in C++).
The functions are not
const-correct, since they accept a string pointer and return a non- pointer within the string.
Also, since the Normative Amendment 1 (C95), functions are considered subsumed by functions, for which reason neither C95 nor any later standard provides wide-character versions of these functions. The argument against is that they do not differentiate between an error and a .
Popular extensions
Replacements
Despite
the well-established need to replace
strcat
[ and ]strcpy
[ 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.
The most popular replacement are the strlcat
and strlcpy
functions, which appeared in OpenBSD
OpenBSD is a security-focused, free and open-source, Unix-like operating system based on the Berkeley Software Distribution (BSD). Theo de Raadt created OpenBSD in 1995 by forking NetBSD 1.0. According to the website, the OpenBSD project em ...
2.4 in December, 1998. 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, encouraging the use of C strings (instead of some superior alternative form of string),[libc-alpha mailing list](_blank)
selected messages from 8 August 2000 thread
/ref> and hiding other potential errors. Consequently, they have not been included in the GNU C library
The GNU C Library, commonly known as glibc, is the GNU Project's implementation of the C standard library. Despite its name, it now also directly supports C++ (and, indirectly, other programming languages). It was started in the 1980s by ...
(used by software on Linux), although they are implemented in the C libraries for OpenBSD, FreeBSD
FreeBSD is a free and open-source Unix-like operating system descended from the Berkeley Software Distribution (BSD), which was based on Research Unix. The first version of FreeBSD was released in 1993. In 2005, FreeBSD was the most popular ...
, NetBSD
NetBSD is a free and open-source Unix operating system based on the Berkeley Software Distribution (BSD). It was the first open-source BSD descendant officially released after 386BSD was forked. It continues to be actively developed and is a ...
, Solaris
Solaris may refer to:
Arts and entertainment Literature, television and film
* ''Solaris'' (novel), a 1961 science fiction novel by Stanisław Lem
** ''Solaris'' (1968 film), directed by Boris Nirenburg
** ''Solaris'' (1972 film), directed by ...
, OS X
macOS (; previously OS X and originally Mac OS X) is a Unix operating system developed and marketed by Apple Inc. since 2001. It is the primary operating system for Apple's Mac computers. Within the market of desktop and lapt ...
, and QNX
QNX ( or ) is a commercial Unix-like real-time operating system, aimed primarily at the embedded systems market. QNX was one of the first commercially successful microkernel operating systems.
The product was originally developed in the early ...
, as well as in alternative C libraries for Linux, such a
libbsd
introduced in 2008, and musl
musl is a C standard library intended for operating systems based on the Linux kernel, released under the MIT License. It was developed by Rich Felker with the goal to write a clean, efficient and standards-conformant libc implementation.
O ...
, introduced in 2011. The lack of GNU C library support has not stopped various software authors from using it and bundling a replacement, among other SDL, GLib
GLib is a bundle of three (formerly five) low-level system libraries written in C and developed mainly by GNOME. GLib's code was separated from GTK, so it can be used by software other than GNOME and has been developed in parallel ever sin ...
, ffmpeg
FFmpeg is a free and open-source software project consisting of a suite of libraries and programs for handling video, audio, and other multimedia files and streams. At its core is the command-line ffmpeg tool itself, designed for processing of vid ...
, rsync
rsync is a utility for efficiently transferring and synchronizing files between a computer and a storage drive and across networked computers by comparing the modification times and sizes of files. It is commonly found on Unix-like operat ...
, and even internally in the Linux kernel
The Linux kernel is a free and open-source, monolithic, modular, multitasking, Unix-like operating system kernel. It was originally authored in 1991 by Linus Torvalds for his i386-based PC, and it was soon adopted as the kernel for the GNU ope ...
. Open source implementations for these functions are available.
Sometimes memcpy
[ or ]memmove
[ 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
The Microsoft Security Development Lifecycle is a software development process used and proposed by Microsoft to reduce software maintenance costs and increase reliability of software concerning software security related bugs. It is based on the ...
, Microsoft introduced a family of "secure" functions including strcpy_s
and strcat_s
(along with many others). 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, which usually aborts the program. Some functions perform destructive operations before calling the runtime-constraint handler; for example, strcat_s
sets the destination to the empty string, 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++
Microsoft Visual C++ (MSVC) is a compiler for the C, C++ and C++/CX programming languages by Microsoft. MSVC is proprietary software; it was originally a standalone product but later became a part of Visual Studio and made available in both tri ...
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. Although open-source implementations of these functions are available, these functions are not present in common Unix C libraries. 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. Usage of has also been suggested as a way to avoid unwanted compiler optimizations.
See also
* source code syntax, including backslash escape sequences
* String functions
* Perl Compatible Regular Expressions
Perl Compatible Regular Expressions (PCRE) is a library written in C, which implements a regular expression engine, inspired by the capabilities of the Perl programming language. Philip Hazel started writing PCRE in summer 1997. PCRE's syntax i ...
(PCRE)
Notes
References
External links
Fast memcpy in C
multiple C coding examples to target different types of CPU instruction architectures
{{CProLang, state=expanded
String handling
String handling
String (computer science)