在字符串文字上使用 strdup 的优点和缺点
我想清楚以下代码的所有优点/缺点:
{
char *str1 = strdup("some string");
char *str2 = "some string";
free(str1);
}
str1:
- 您可以修改字符串的内容
str2:
- 您不必使用 free()
- 更快
还有其他区别吗?
I want to be clear about all the advantages/disadvantages of the following code:
{
char *str1 = strdup("some string");
char *str2 = "some string";
free(str1);
}
str1:
- You can modify the contents of the string
str2:
- You don't have to use free()
- Faster
Any other differences?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果可以的话,不要使用任何一个,如果您从不打算修改它,请通过以下
str3
之一来避免它,如果您打算修改它,则通过str4
来避免它。str3
确保程序中的其他函数无法修改您的字符串(字符串文字可以共享和可变)。str4
在堆栈上分配一个常量大小的数组,因此分配和释放没有任何开销。系统只需复制您的数据即可。Use neither if you can and avoid it by one of the following
str3
if you never plan to modify it andstr4
if you do.str3
ensures that no other function in your program can modify your string (string literals may be shared and mutable).str4
allocates a constant sized array on the stack, so allocation and deallocation comes with no overhead. The system has just to copy your data.使用原始字符串 - 无论它是源中的文字、内存映射文件的一部分,甚至是程序另一部分“拥有”的分配字符串 - 都具有节省内存的优点,并可能消除您遇到的难看的错误情况。否则,如果您执行了分配(可能会失败),则必须进行处理。当然,缺点是您必须跟踪以下事实:该字符串不由当前使用它的代码“拥有”,因此无法修改/释放它。有时,这意味着您需要在结构中使用一个标志来指示它使用的字符串是否已分配给该结构。对于较小的程序,这可能只意味着您必须通过多个函数手动遵循字符串所有权的逻辑并确保其正确。
顺便说一句,如果字符串将由结构使用,一种避免必须保留标记是否已为结构分配的标志的好方法是为结构和字符串分配空间(如果需要) ),只需调用一次
malloc
即可。然后,释放结构总是有效的,无论字符串是为结构分配的还是从字符串文字或其他源分配的。Using the original string - whether it's a literal in the source, part of a memory-mapped file, or even an allocated string "owned" by another part of your program - has the advantage of saving memory, and possibly eliminating ugly error conditions you'd otherwise have to handle if you performed an allocation (which could fail). The disadvantage, of course, is that you have to keep track of the fact that this string is not "owned" by the code currently using it, and thus that it cannot be modified/freed. Sometimes this means you need a flag in a structure to indicate whether a string it uses was allocated for the structure or not. With smaller programs, it might just mean you have to manually follow the logic of string ownership through several functions and make sure it's correct.
By the way, if the string is going to be used by a structure, one nice way to get around having to keep a flag marking whether it was allocated for the structure or not is to allocate space for the structure and the string (if needed) with a single call to
malloc
. Then, freeing the structure always just works, regardless of whether the string was allocated for the structure or assigned from a string literal or other source.ANSI C->不可移植
ANSI C -> not portable