为什么的strdup认为是邪恶

为什么的strdup认为是邪恶

本文介绍了为什么的strdup认为是邪恶的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了一些海报,说明的strdup 是邪恶的。是否有这样的共识?我用它没有任何负罪感和可以看到没有理由比使用的malloc / 的memcpy 更糟。

I've seen some posters stating that strdup is evil. Is there a consensus on this? I've used it without any guilty feelings and can see no reason why it is worse than using malloc/memcpy.

我认为可能赚取的唯一的事情的strdup 的声誉是,来电者可能会滥用它(如没有意识到他们必须释放内存退换;尝试strcat的到一个strdup'ed字符串的结尾)。但随后malloc分配字符串不被滥用的可能性,无论是免费的。

The only thing I can think might earn strdup a reputation is that callers might misuse it (eg. not realise they have to free the memory returned; try to strcat to the end of a strdup'ed string). But then malloc'ed strings are not free from the possibility of misuse either.

感谢您的答复,并表示歉意那些谁考虑的问题无益(票关闭)。在答复的总结,似乎没有一般的感觉,的strdup 是邪恶的本身,而是一个普遍的共识,它可以和C一样的许多其他部分,是不当或不安全使用。

Thanks for the replies and apologies to those who consider the question unhelpful (votes to close). In summary of the replies, it seems that there is no general feeling that strdup is evil per se, but a general consensus that it can, like many other parts of C, be used improperly or unsafely.

有没有正确答案真的,但对于接受一个起见,我接受了@ nneoneo的答案 - 它可能同样已经@R ..的答案

There is no 'correct' answer really, but for the sake of accepting one, I accepted @nneoneo's answer - it could equally have been @R..'s answer.

推荐答案

有两个原因,我能想到的:

Two reasons I can think of:


  1. 这不是严格的ANSI C,而是POSIX。因此,一些编译器(如MSVC)不鼓励使用(MSVC prefers _strdup )和技术上的C标准可以定义自己的的strdup ,因为 STR 是一个保留preFIX。所以,也有一些潜在的可移植性担忧其使用。

  2. 它隐藏它的内存分配。大多数其他 STR 函数不分配内存,因此用户可能会被误导(如你所说)相信返回的字符串并不需要被释放。

  1. It's not strictly ANSI C, but rather POSIX. Consequently, some compilers (e.g. MSVC) discourage use (MSVC prefers _strdup), and technically the C standard could define its own strdup with different semantics since str is a reserved prefix. So, there are some potential portability concerns with its use.
  2. It hides its memory allocation. Most other str functions don't allocate memory, so users might be misled (as you say) into believing the returned string doesn't need to be freed.

但是,除了这几点,我认为谨慎使用的strdup 是有道理的,因为它可以减少code复制,并提供了一​​个很好的实现,共同成语(如的strdup(字符串常量)来得到一个字符串的可变的,可回收的复印件)。

But, aside from these points, I think that careful use of strdup is justified, as it can reduce code duplication and provides a nice implementation for common idioms (such as strdup("constant string") to get a mutable, returnable copy of a literal string).

这篇关于为什么的strdup认为是邪恶的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 17:09