Yesterday, I had my Unit Test. One of the programs was to copy strings and find out its length without the string functions. This was the code I wrote:
#include <stdio.h>
int main(){
char str1[100], str2[100] = {'a'};
printf("Enter a string\n");
fgets(str1, sizeof(str1), stdin);
int i;
for(i = 0; str1[i] != '\0'; i++){
str2[i] = str1[i];
}
str2[i] = '\0';
printf("Copied string = %s", str2);
printf("Length of string = %d", i-1);
}
I had a rather surprising observation! Even if a commented str2[i] = '\0'
, the string would be printed correctly i.e., without the extra 'a'
s in the initialization which should not be overwritten as per my knowledge.
After commenting str2[i] = '\0'
, i expected to see this output:
test
Copied string = testaaaaaaaaaaaaaaaaaaaaaaaaaaa....
Length of string = 4
This is the output:
test
Copied string = test
Length of string = 4
How is str2
printed correctly? Is it the fact that the compiler recognized the copying of the string and silently added the null termination? I am using gcc but clang also produces similar output.