xiaokaoy
xiaokaoy

Reputation: 1696

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?

Upvotes: 51

Views: 21808

Answers (2)

Despertar
Despertar

Reputation: 22352

To point out some nuances related to C strings.

The char array sizeof will be 5, but the string will normally be "seen" as 3 chars + 1 null terminator. The extra null terminator won't be seen.

This is because strings are walked until the FIRST null terminator is encountered. This is why strlen will be 3 and not 4. The 3 letters are counted, and when it hits the null terminator that signifies the end of the string, so it stops.

When passing the char[] to a function, it will decay into a char*, so the fact that the original char[] was a size of 5 is further lost.

HOWEVER...if you passed the sizeof(a) into a function, then the extra null could cause issues, and of course should not be included in the string literal.

#include <string.h>
#include <stdio.h>

void main() {
    char a[] = "abc\0";
    printf("sizeof: %lu\n", sizeof(a));
    printf("strlen: %lu\n", strlen(a));
}

Output:

sizeof: 5
strlen: 3

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612794

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.

Upvotes: 78

Related Questions