Given a string , say ,
char *str = "Hello,StackOverflow!"
char newStr[30];
int l = strlen(str);
for(int i =0 ; i<l ; i ++ )
newStr[i] = str[i];
printf("%s" , newStr);
Now , we know that the last character of a c-string has to be '\0' , Since here we haven't explicitly done the same ( store '\0' at last index of string newStr) , this program should crash since printf won't find the end of string.
But I noticed that it was working fine sometimes and sometimes it wasn't. What could be the problem ? It was working almost everytime actually. Isn't it supposed to crash or give some run-time error?
Will it be the same case in C++ too ?
printfroutine will continue to print until it hits an unrelated zero byte, which is often soon enough. Strictly speaking, it will likely be accessing memory outside the program's designated memory block, but blocks are fairly coarsely allocated, so you might not get an access violation most of the time.