不以N结尾的C样式字符串 [英] Not null-terminating a C-style string

查看:78
本文介绍了不以N结尾的C样式字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个字符串,比如说,

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);

现在,我们知道c字符串的最后一个字符必须是'\0',因为这里我们还没有明确地做同样的事情(将'\0'存储在字符串newStr的最后一个索引中),该程序应该崩溃,因为printf找不到

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?

在C ++中也是如此吗?

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.

此外,给出运行时错误-好吧,这取决于做什么您的意思是运行时错误。 C没有动态运行时-如果您期望异常产生格式正确的错误消息,则不会发生这种情况。可能会发生分段错误。

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.

这篇关于不以N结尾的C样式字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆