Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are all char arrays automatically null-terminated?

Probably I'm just too dump for googling, but I always thought char arrays get only null terminated by an literal initialization (char x[]="asdf";) and got a bit surprised when I saw that this seems not to be the case.

int main()
{
    char x[2];
    printf("%d", x[2]);
    return 0;
}

Output: 0

Shouldn't an array declared as size=2*char actually get the size of 2 chars? Or am I doing something wrong here? I mean it isn't uncommon to use a char array as a simple char array and not as a string, or is it?

like image 946
user1329846 Avatar asked Jun 27 '12 15:06

user1329846


People also ask

Can a char array be null?

You can't initialise a char array with NULL , arrays can never be NULL .

Are C strings automatically null terminated?

C strings are null-terminated. That is, they are terminated by the null character, NUL . They are not terminated by the null pointer NULL , which is a completely different kind of value with a completely different purpose. NUL is guaranteed to have the integer value zero.

Does char include null terminator?

char * strchr ( const char * string, int c ); Find character in string. Returns the first occurrence of c in string. The null-terminating character is included as part of the string and can also be searched.

Are strings always null terminated?

Yes - although your question sounds like you suspect otherwise... Yes, all string in C are represented by string 0 terminated. @AditiRawat '\0' is just a char with value 0, it can be checked against 0.


2 Answers

char arrays are not automatically NULL terminated, only string literals, e.g. char *myArr = "string literal";, and some string char pointers returned from stdlib string methods.

C does no bounds checking. So an array declared as size 2*char gives you 2 memory slots that you can use, but you have the freedom to walk all over the memory on either side of that, reading and writing and thereby invoking undefined behavior. You may see 0 bytes there. You may write to array[-1] and crash your program. It is your responsibility to keep track of the size of your array and avoid touching memory that you didn't allocate.

It is common to use a char array as a simple char array, i.e. other than a C string, for instance, to hold any arbitrary buffer of raw bytes.

like image 156
pb2q Avatar answered Sep 21 '22 21:09

pb2q


You are accessing an uninitialized array outside its bounds. That's double undefined behavior, anything could happen, even getting 0 as output.

In answer to your real question: Only string literals get null-terminated, and that means that char x[]="asdf" is an array of 5 elements.

like image 38
K-ballo Avatar answered Sep 19 '22 21:09

K-ballo