Not null-terminating a C-style string

二次信任 提交于 2019-12-02 04:43:57

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.

A "crash" is not guaranteed. A program that improperly handles null terminators in strings - more generally accesses data outside of buffer boundaries - or violates the printf format string, may seem to work just fine, functioning and not e.g. causing a segfault. But this is just happenstance: the behavior of your code is undefined.

It will be the same in C++.

I would suspect that most of the time it would keep printing past the "!" and keep going in memory until it hits a NULL. Which could result in a crash, but doesn't have to.

This is why it's best to either:

memset(newStr, 0, 30);

or

// This works because string literals guarantee a '\0' is present
// but the strlen returns everything up until the '\0'
int l = strlen(str) + 1;

this works too, but I don't feel it's as clear as adding one to strlen:

for(i =0 ; i<=l ; i ++ )

As the defination of strlen implies you need to.

By chance, most of the time the uninitialized bytes in newStr happen to be 0 in your particular case.

Your program has undefined behaviour, since you promise to call printf with a pointer to a null-terminated string but fail to do so. Anything could happen, but your program is simply not correct.

Specifically, while reading the array elements one by one to find the null terminator, the program will eventually access an uninitialized variable, which is UB.

The behaviour of reading bytes that have not been initialized as characters is undefined in most implementations of C. Sometimes printf may write garbage, sometimes the program may find a null byte \0 after the last character and terminate normally. In some rare cases it may cause a crash. This is why you are seeing variation in what happens when you run the program. It depends on the compiler you are using, and what was in the memory location following that which you are allocating for the array.

(That is, if your program would compile - you've left off a semicolon)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!