【发布时间】:2014-08-12 18:14:38
【问题描述】:
在对问题Reading In A String and comparing it C的回复中,不止一个人不鼓励使用strcmp(),比如
我也强烈建议你习惯使用 strncmp() 现在,...以避免许多问题。
或(在Why does my string comparison fail?)
确保您使用的是 strncmp 而不是 strcmp。 strcmp 是深刻的 不安全。
他们暗指什么问题?
之所以scanf() with string specifiers 和gets() are strongly discouraged 是因为它们几乎不可避免地会导致缓冲区溢出漏洞。但是,strcmp() 不可能溢出缓冲区,对吧?
“缓冲区溢出或缓冲区溢出是程序在向缓冲区写入数据时超出缓冲区边界并覆盖相邻内存的异常情况。”
( -- Wikipedia: buffer overflow).
由于 strcmp() 函数从不写入任何缓冲区,所以 strcmp() 函数不会导致缓冲区溢出,对吧?
人们不鼓励使用strcmp(),而是推荐strncmp() 的原因是什么?
【问题讨论】:
-
你为什么不问问那些人?
-
相信我。
strncmp()并不比strcmp()好(或差)。 -
链接的SO文章中的cmets大多是垃圾
-
使用
strncmp来防止非空终止的字符串只是解决了根本问题,即您有一个未终止的字符串。它只会弄乱下一个假设它是空终止的函数。
标签: c string deprecated strcmp