A string in C is an array of char that ends with a zero byte, written '\0' and called the null terminator. C has no separate string type, so every string function relies on that terminator to find where the text stops.
The sections below show how to declare a string, how big the array must be, how to copy and measure it, and the mistakes that cause garbage output and buffer overflows.
What is a string in C?
The C library documents a string as a "null-terminated byte string": a sequence of nonzero bytes followed by a byte with value zero. The character array {'c','a','t','\0'} holds the string "cat". Four bytes of storage, three characters of text.
Nothing in the language stops you from storing other things in a char array. It only becomes a string when a zero byte follows the text. Functions such as strlen, strcpy, printf("%s") and puts read forward from the first character until they meet that zero byte. They have no way to know the real size of the array.
How to declare a string in C
There are three common forms. They are not equivalent.
char a[] = "Hello"; /* array of 6 chars: H e l l o \0 */
char b[20] = "Hello"; /* array of 20 chars: Hello, then \0, then zeros */
const char *c = "Hello"; /* pointer to a string literal */
In the first form the compiler counts the literal for you. "Hello" is five letters, and the array gets six elements because the terminator is included. The second form reserves extra room, and the elements after the text are filled with zeros. The third form does not create an array of your own at all: it points at the literal, which the program owns.
Array versus pointer: what you can change
The contents of an array initialized from a literal are yours to modify. A string literal itself is not. The cppreference page on string literals says that modifying the array behind a literal is undefined behavior, because literals may be placed in read-only memory.
char a[] = "Hello";
a[1] = 'M'; /* fine: a is a copy you own */
char *p = "Hello";
p[1] = 'M'; /* undefined behavior: writes into a literal */
Declare pointers to literals as const char *. Then the compiler rejects the second assignment instead of letting it crash at run time.
How big does the array need to be?
One more than the number of characters you want to store. The extra element is the terminator. This is the most common source of off-by-one bugs with strings.
| Declaration | Array size | Terminator stored? |
|---|---|---|
char s[] = "abc"; | 4 | Yes |
char s[4] = "abc"; | 4 | Yes |
char s[10] = "abc"; | 10 | Yes, followed by zeros |
char s[3] = "abc"; | 3 | No |
The last row is legal C. When the array is exactly as long as the text, the initializer drops the terminator, and you have a character array that is not a string. Passing it to printf("%s", s) or strlen reads past the end of the array, which is undefined behavior. The compiler may warn about it, but you can't count on that.
Reading the length: strlen versus sizeof
strlen returns the number of characters before the first null byte, as a size_t. It does not count the terminator. sizeof on an array gives the size of the whole array in bytes.
#include <stdio.h>
#include <string.h>
int main(void)
{
char s[20] = "Hello";
printf("strlen: %zu\n", strlen(s)); /* 5 */
printf("sizeof: %zu\n", sizeof s); /* 20 */
return 0;
}
Example output:
strlen: 5
sizeof: 20
strlen walks the string one byte at a time, so it takes time proportional to the length. Store the result in a variable if you use it in a loop condition. And remember that sizeof only reports the array size where the name still refers to an array. Inside a function that receives char *s, sizeof s is the size of the pointer, not of the text. The article on arrays in C covers why.
A literal can also contain a zero byte inside it. "abc\0def" is an array of 8 chars, but strlen reports 3, because it stops at the first zero.
How to copy a string in C
You cannot copy a string with =. For arrays, b = a does not compile, and for pointers it copies the address, so both names refer to the same text. Use strcpy or a bounded alternative.
char src[] = "Hello";
char dest[6];
strcpy(dest, src);
strcpy copies the source including its terminator. The standard says the behavior is undefined if the destination is not large enough, so you must make sure it holds strlen(src) + 1 bytes. It does not check, and it is also undefined if the two strings overlap.
strncpy does not always terminate
strncpy looks like the safe version, but it has a trap. If the source is longer than the count you give it, the copy stops at the count and the result is not null-terminated. If the source is shorter, it pads the rest of the destination with zeros up to the count.
char dest[6];
strncpy(dest, "Hello, world", sizeof dest - 1);
dest[sizeof dest - 1] = '\0'; /* terminate it yourself */
Without that last line, dest would hold Hello and no terminator in the sixth element, and anything that read it as a string would run off the end. Writing the terminator yourself after every strncpy is the habit that avoids this. C11 also defines optional bounds-checked functions such as strcpy_s and strncpy_s, but they are only available if the implementation defines __STDC_LIB_EXT1__, and many compilers do not.
A common alternative is snprintf, which always terminates the output when the buffer size is greater than zero:
snprintf(dest, sizeof dest, "%s", "Hello, world"); /* dest holds "Hello" */
How to compare strings in C
if (a == b) compares two addresses, not two texts. Use strcmp, which returns 0 when the strings are equal. The details, including the sign of the result, are in strcmp in C.
How to read a string from the keyboard
Reading into a char array has the same sizing problem as copying: the destination must be big enough for the input plus the terminator. fgets takes the buffer size and always terminates the result, which makes it the usual choice. See fgets in C for how it handles the trailing newline. If you use scanf("%s", ...) with no width limit, a long enough input overflows the array, as described in scanf in C.
Strings of unknown length
When the text length is not known at compile time, allocate the array on the heap with room for the terminator, and free it when you are done:
size_t length = strlen(src);
char *copy = malloc(length + 1); /* + 1 for the terminator */
if (copy == NULL) {
/* handle the allocation failure */
}
else {
memcpy(copy, src, length + 1); /* copies the terminator too */
/* use copy */
free(copy);
}
Forgetting the + 1 is the classic one-byte overflow. More on allocation and ownership is in malloc in C.
Common string bugs and what they look like
- Garbage after the text. The array has no terminator, so output keeps reading memory until it hits a zero byte. Check for
char s[3] = "abc"or an unterminatedstrncpy. - Crash when you edit a string. You wrote through a
char *that points at a literal. Switch to achararray. - Comparison is always false. You compared pointers with
==. Usestrcmp. - Corrupted neighbouring variables. A copy wrote past the end of the destination. Check the destination size against
strlen(src) + 1. - Wrong length from a function parameter.
sizeofon achar *parameter gives the pointer size. Pass the length in, or callstrlen.
Compilers can catch some of these. Building with -Wall -Wextra on GCC or Clang flags several of them, and AddressSanitizer (-fsanitize=address) reports overflows at run time. Neither catches everything, so the sizing rule is the real defense: the buffer holds the characters plus one.
Characters beyond ASCII
A char is one byte. Text in UTF-8 uses between one and four bytes per character, so strlen counts bytes, not characters. A literal such as "a猫🍌" is an array of 9 chars in UTF-8: 8 bytes of text and the terminator. If you need to count visible characters, strlen is the wrong tool, and you need a library that understands the encoding. For the byte-level functions in this article the distinction does not matter, since copying and comparing bytes works the same.
If it still misbehaves
Print the array size and the length side by side with sizeof and strlen. If the length is larger than the size minus one, the terminator is missing or was overwritten. Then look at the last write to that buffer: a copy, a read, or an off-by-one loop. See pointers in C if the pointer-versus-array distinction above still feels unclear.
Frequently asked questions
- Does C have a string type?
- No. C has no built-in string type. A string is a convention: an array of char whose last meaningful element is a zero byte, written '\0' and called the null terminator. The standard library functions in string.h all rely on that convention to know where a string ends.
- What is the difference between strlen and sizeof for a string?
- strlen counts the characters before the first null byte and does not count the terminator. sizeof on a char array gives the size of the whole array in bytes, including the terminator and any unused space. For char s[] = "hi", strlen(s) is 2 and sizeof s is 3.
- Why does my string print garbage after the text?
- The array probably has no null terminator, so printf and puts keep reading memory past the end until they happen to find a zero byte. This happens when an array is exactly as long as its text (char s[3] = "abc"), or when strncpy copies a source that is longer than its count.
- Can I change a string stored in a char pointer?
- Not if the pointer points at a string literal. Modifying a string literal is undefined behavior, because literals may live in read-only memory. Use a char array initialized from the literal, such as char s[] = "Hello", which is a modifiable copy.