Ç的strcpy() - 邪恶? [英] C strcpy() - evil?

查看:142
本文介绍了Ç的strcpy() - 邪恶?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有些人似乎认为C的的strcpy()功能不好或邪恶的。尽管我承认这是通常最好使用函数strncpy()为了避免缓冲区溢出,下面(的实施的strdup()对于那些不幸运,有它的功能),安全地使用的strcpy()和应该的从不的溢出:

Some people seem to think that C's strcpy() function is bad or evil. While I admit that it's usually better to use strncpy() in order to avoid buffer overflows, the following (an implementation of the strdup() function for those not lucky enough to have it) safely uses strcpy() and should never overflow:

char *strdup(const char *s1)
{
  char *s2 = malloc(strlen(s1)+1);
  if(s2 == NULL)
  {
    return NULL;
  }
  strcpy(s2, s1);
  return s2;
}

* S2 是保证有足够的空间来存储 * S1 ,并使用的strcpy()让我们可以不用到的strlen()结果存储在另一个函数以后使用的不必要的(在这种情况下)长度参数到函数strncpy()。然而,有些人写与函数strncpy这个函数(),甚至的memcpy(),这都需要一个长度参数。我想知道别人怎么想这个问题。如果你觉得的strcpy()是在特定情况下的安全,这样说。如果你有一个很好的理由不使用的strcpy()在这种情况下,请给它 - 我想知道为什么它可能是更好地使用函数strncpy()的memcpy()在这样的情况。如果你觉得的strcpy()是好的,但不是在这里,请解释。

*s2 is guaranteed to have enough space to store *s1, and using strcpy() saves us from having to store the strlen() result in another function to use later as the unnecessary (in this case) length parameter to strncpy(). Yet some people write this function with strncpy(), or even memcpy(), which both require a length parameter. I would like to know what people think about this. If you think strcpy() is safe in certain situations, say so. If you have a good reason not to use strcpy() in this situation, please give it - I'd like to know why it might be better to use strncpy() or memcpy() in situations like this. If you think strcpy() is okay, but not here, please explain.

基本上,我只是想知道为什么有些人使用的memcpy()当别人用的strcpy()和还有一些使用纯函数strncpy()。是否有任何逻辑preferring一个比三(不考虑前两种的缓冲检查)?

Basically, I just want to know why some people use memcpy() when others use strcpy() and still others use plain strncpy(). Is there any logic to preferring one over the three (disregarding the buffer checks of the first two)?

推荐答案

的memcpy 可以比的strcpy 更快, 函数strncpy ,因为它不具有对每个复制字节与比较'\\ 0',并且因为它已经知道复制的对象的长度。它可以在与达夫设备的类似的方式来实现,或者使用在复制几个字节汇编指令一时间,像MOVSW和MOVSD

memcpy can be faster than strcpy and strncpy because it does not have to compare each copied byte with '\0', and because it already knows the length of the copied object. It can be implemented in a similar way with the Duff's device, or use assembler instructions that copy several bytes at a time, like movsw and movsd

这篇关于Ç的strcpy() - 邪恶?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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