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 ?
No. It invokes undefined behavior – it means it doesn’t have to crash – it can do literally anything, like nasal demons.
Also, “gives a runtime error” – well, that depends on what do you mean by a runtime error. There’s no dynamic runtime for C – if you expect a nicely formatted error message from an exception, that wouldn’t happen. What would happen is most likely a segmentation fault.
All in all, if one causes/uses undefined behavior, he must not rely on it crashing or not crashing.