Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do string literals that end with a null-terminator contain an extra null-terminator?

For example:

char a[] = "abc\0";

Does standard C say that another byte of value 0 must be appended even if the string already has a zero at the end? So, is sizeof(a) equal to 4 or 5?

like image 642
xiaokaoy Avatar asked Jul 30 '13 09:07

xiaokaoy


People also ask

Do string literals have null terminator?

All string literals have an implicit null-terminator, irrespective of the content of the string. The standard (6.4. 5 String Literals) says: A byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals.

Why do C strings end with a null terminator?

Because in C strings are just a sequence of characters accessed viua a pointer to the first character. There is no space in a pointer to store the length so you need some indication of where the end of the string is. In C it was decided that this would be indicated by a null character.

What is a series of characters that ends with a null terminator character called?

Strings are actually one-dimensional array of characters terminated by a null character '\0'.

What does a null terminator do?

A null-terminated string means that the end of your string is defined through the occurrence of a null-char (all bits are zero).


1 Answers

All string literals have an implicit null-terminator, irrespective of the content of the string.

The standard (6.4.5 String Literals) says:

A byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals.

So, the string literal "abc\0" contains the implicit null-terminator, in addition to the explicit one. So, the array a contains 5 elements.

like image 164
David Heffernan Avatar answered Oct 26 '22 09:10

David Heffernan