Hi
In the following code, I copy a string in to a char* str, which is 10 characters long, using strncpy()
.
Now according to strncpy()
manual, "Warning: If there is no null byte among the first n bytes of src, the string placed in dest will not be null terminated. " which is exactly what happens here.
The source string is 26 charcters long and I have copied 10 characters, hence no null character is placed at then end of str.
But when I print the contents of str, starting from 0 until I get '\0', it behaves normally.
Why? When there is no '\0' placed at the end then why does the loop stop at the correct place?
What I understand is that it should give "Segmentation fault" or at least it shouldn't stop there and keep printing 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 output :
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 will be appreciated.
EDIT
Is there a proper way to check whether a string ends at '\0' or not? I always thought the above loop to be the ultimate test, but now it seems it isn't.
Lets say we get a string from some function developed by other programmer. Now how will we know that it ends at correct place with '\0'. May be it doesn't, then it will go beyond the actual size until we get some '\0'. We can never know the actual size of the string.
So how do we tackle such situation?
Any suggestion?