C中的空终止字符串 [英] Null terminated string in C

查看:87
本文介绍了C中的空终止字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很担心 C 中的字符串.我需要设置最后一个字符 \0 还是它自己设置?如果我不手动执行,那么当我尝试调试代码以及​​访问 string1[257] 时它不为空.我在释放字符串数组的分配内存时遇到问题,所以我认为这是一个原因.

I am quite anxious about strings in C. Do I need to set the last char \0 or it does it by it self? If I don't do it manually then when I try to debug code and when I access string1[257] it is not null. I am having problems with freeing allocated memory of an array of strings so I thought it was a reason.

char string1[257], string2[257];
scanf("%s", &string2);
string1[257] = '\0';
strncpy(string1, string2, 257);
string1[257] = '\0'; /* do I need to do that? */

推荐答案

是否绝对有必要?,因为当你调用scanf时,strcpy(除了strncpy你需要手动置零,如果它超过大小),它会为您复制空终止符.无论如何这样做好吗?不是真的,它并没有真正帮助解决缓冲区溢出问题,因为这些函数无论如何都会超过缓冲区的大小.那么最好的方法是什么?将 C++ 与 std::string 一起使用.

Is it absolutely necessary? No, because when you call scanf, strcpy(except for strncpy where you need to manually put zero if it exceeds the size), it copies the null terminator for you. Is it good to do it anyways? Not really, it doesn't really help the problem of bufferoverflow since those function will go over the size of the buffer anyways. Then what's the best way? use c++ with std::string.

顺便说一下,如果您访问/写入 string1[257],那将超出范围,因为您正在访问/写入数组中的 258 个元素大小为 257.(它是基于 0 的索引)

By the way, if you access/write to string1[257], that will be out of bound since you're accessing/writing 258th element in an array of size 257. (it's 0-based index)

这篇关于C中的空终止字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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