strncmp比strcmp的优势? [英] Advantages of strncmp over strcmp?

查看:386
本文介绍了strncmp比strcmp的优势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎通常建议使用strncmpstrcmp,这有什么好处?我认为这可能与安全性有关.在这种情况下,如果已知输入字符串之一是文字常量(例如"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的优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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