In the following code, I will copy the string to a char * string with a length of 10 characters using strncpy() .
Now, according to the strncpy() instruction "Warning: if the first n bytes of src do not have a null byte, the line placed in dest will not be null terminated." This is exactly what is happening here.
The original string is 26 characters long, and I copied 10 characters, so the null character does not fit at the end of the line.
But when I print the contents of the line, starting from 0 until getting "\ 0", this behaves fine.
Why? When there is no "\ 0" at the end, why does the loop stop at the right place?
I understand that it should give "Segmentation Error" or, at least, it should not stop there and continue to print some garbage values.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define SIZE 10 int main() { char *str ; str = malloc( sizeof( char ) * SIZE ); if( str == NULL ) exit( 1 ); memset( str, 0, sizeof( char ) * SIZE ); strncpy( str, "abcdefghijklmnopqrstuvwxyz", sizeof( char ) * SIZE ); unsigned int index; for( index = 0; str[ index ] != '\0' ; index++ ) { printf( "str[ %u ] has got : %c \n ", index, str[ index ] ); } return 0; }
Here is the result:
str [0] has got: a
str [1] has got: b
str [2] has got: c
str [3] has got: d
str [4] has got: e
str [5] has got: f
str [6] has got: g
str [7] has got: h
str [8] has got: i
str [9] has got: j
Any help would be appreciated.
EDIT
Is there a way to check if a string ends with '\ 0' or not? I always thought the above loop is the final test, but now it doesn't seem to be that way.
Suppose we get a string from some function developed by another programmer. Now, as we find out that it ends in the right place with '\ 0'. Maybe this does not happen, then it will go beyond the actual size until we get "\ 0". We will never know the actual row size.
So how do we solve this situation?
Any suggestion?