哪种方式为字符串保留内存?
我创建了一个宏来为 C 中的字符串保留内存。它看起来像这样:
#define newString(size) (char*)malloc(sizeof(char) + size)
那么我有什么理由不应该在我自己的个人项目中使用这个宏呢?我知道我不应该在生产代码中这样做,因为它需要每个人都有该头文件,并且每个人都知道 newString 是一个宏。
I have created a macro to make reserve memory for my strings in C. It looks like this:
#define newString(size) (char*)malloc(sizeof(char) + size)
So is there any reason I shouldn't use this macro in my own personal projects? I know I shouldn't do this in production code because it would require everyone to have that header file and everyone to know that newString
was a macro.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
(char*)malloc(sizeof(char) * (size+1))
会更合适(+1 是为了考虑字符串末尾的 NULL,如果适用)。如果要复制字符串, strlen() 不会考虑 NULL 终止字符串,因此需要额外的内存
char
。(char*)malloc(sizeof(char) * (size+1))
would be more appropriate (the +1 is to account for the NULL at the end of string, if applicable).If one is copying a string, strlen() doesn't account for the NULL terminating the string hence an additional memory
char
is required.我不太确定使用预处理器来节省一些打字是个好主意。 (那条路既黑暗又可怕。)用不了多久,您就会想要向宏中添加一些内容,并且您将开始遇到难以调试的问题。
如果您正在滚动自己的内存管理,请使用真实的函数并提供免费的“删除”函数。
如果您担心性能,您的编译器足够智能,可以为您内联小函数。
I'm not so sure it's a good idea to use the preprocessor to save yourself some typing. (That road is dark and scary.) It won't be long before you'll want to add something to your macro, and you'll start running into problems that will be way hard to debug.
If you're rolling your own memory management, then use a real function and provide a complimentary "delete" function.
If you're worried about performance, your compiler is smart enough to inline little functions for you.
您应该检查分配是否成功。
但是使用宏没有问题
You should check if the allocation was successful.
But there is no problem in using a macro
主要原因是
sizeof(char)
被定义为始终为 1。因此您应该改为:并且这样写会比
newString(size)
更短。另外,malloc
返回一个void *
,您不需要在 C 中对其进行转换。另一个原因是您不需要编写
+
> 当您指的是*
时。The main reason is that
sizeof(char)
is defined to always be 1. So you should write instead:and it will be shorter to write this than
newString(size)
. Also,malloc
returns avoid *
which you don't need to cast in C.The other reason is so you don't write a
+
when you mean*
.您的宏相当于
在 C 中,您不需要转换
malloc
的结果,并且sizeof(char)
根据定义等于1
。所以它并不能真正节省你太多的打字时间。我建议不要这样做,即使在您的个人项目中也是如此,因为我认为它没有任何好处。Your macro is equivalent to
as in C you don't need to cast the result of
malloc
andsizeof(char)
equals1
by definition. So it doesn't really save you much typing. I would recommend against it, even in your personal projects, as I don't see any benefit to it.