strncmp比strcmp的优势?

编程入门 行业动态 更新时间:2024-10-25 14:26:54
本文介绍了strncmp比strcmp的优势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

似乎通常建议使用strncmp比strcmp,这有什么好处?我认为这可能与安全性有关.在这种情况下,如果已知输入字符串之一是文字常量(例如"LiteralString"),是否仍然适用?

Seems strncmp is usually recommended than strcmp, what are the advantages? I think it could be related to security. If this is the case, is it still applicable if one of the input string is known to be literal constant, like "LiteralString"?

更新: 我的意思是,在需要比较整个字符串的同一用户场景下,strncmp可以按以下方式使用.我想知道这是否有意义.

UPDATE: I mean under the same user scenario where whole strings need to be compared, and strncmp can be used as below. I am wondering it makes sense or not.

strncmp(inputString, "LiternalString", strlen("LiternalString"));

推荐答案

strcmp的问题是,有时会错误地传递的参数不是有效的C字符串(这意味着p1或p2不会终止)带有空字符(即不是以NULL终止的字符串),然后,strcmp继续比较直到它会到达无法访问的内存并崩溃,有时甚至会导致意外的行为.

The problem with strcmp is that sometimes, if by mistake, arguments that are passed are not valid C-strings (meaning that p1 or p2 is not terminated with a null character i.e. not NULL-terminated String), then, strcmp continues comparing until it reaches non-accessible memory and crashes or sometimes results to an unexpected behaviour.

使用strncmp,您可以限制搜索,以使搜索不会到达无法访问的内存.

Using strncmp you can limit the search, so that it doesn't reach non-accessible memory.

但是,由此不能得出结论,strcmp使用不安全.两种功能均按预期的方式工作良好.程序员在使用该功能之前应阅读该页面的man页,并且在将参数传递给此类库函数时必须足够真诚.

But, from that it should not be concluded that strcmp is insecure to use. Both the functions works well in the way they are intended to work. Programmer should read man page for that function before using it and must be sincere enough when passing parameters to such library functions.

您还可以阅读这,其中几乎包含类似的问题.

You can also read THIS which contains an almost similar question.

更多推荐

strncmp比strcmp的优势?

本文发布于:2023-10-28 13:22:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1536755.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:优势   strncmp   strcmp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!