[Solved] Null terminated C character arrays


First, "sample" is called a string literal. It declares a const char array terminated with a null character.

Let us go on:

    char arr[]="sample";

The right hand part in a const char array of size 7 (6 characters and a '\0'. The dimension of arr is deduced from its initialization and is also 7. The char array is then initialized from the literal string.

    char arr2[6]="sample";

arr2 has a declared size of 6. It is initialized from a string literal of size 7: only the 6 declared position are initialized to {'s', 'a', 'm', 'p', 'l', 'e'} with no terminating null. Nothing is wrong here, except that passing arr2 to a function that expects a null terminated string invokes Undefined Behaviour.

    char arr3[7]="sample";

Declared size an initialization literal string size are both 7: it is just an explicit version of the first use case. Rather dangerous because if you later add one character to the initialization string you will get a not null terminated char array.

    char* strarr="sample";  

Avoid that. You are declaring a non const char pointer on a string literal. While the standard declares explicitely:

If the program attempts to modify such an array, the behavior is
undefined.

strarr[3] = 'i' would then invoke Undefined Behaviour with no warning. That being said and provided you never modify the string, you have a nice null terminated string.

    char* strarr1=arr;

Ok, you declare a pointer to another string. Or more exactly a pointer to the first character of another string. And it is correctly null terminated.

    char* strarr2=arr2; 

You have a pointer to the first character of a not null terminated char array… You could not pass arr2 to a function expecting a null terminated char array, and you cannot either pass strarr2.

    char* strarr3=arr3;

You have another pointer pointing to a string. Same behaviour as strarr1.


As per how to check in gdb for the terminating null, you cannot print it directly, because gdb knows enough of C strings to automatically stop printing a string on first null character. But you can always use p arr[7] to see whether the character after the array is a null or not.

For arr2, arr2+7 is one past the array. So it is undefined what lies there and in a truely bad system, using p arr[7] could raise a signal because it could be after the end of a memory segment – but I must admit that I have never seen that…

9

solved Null terminated C character arrays