简体   繁体   English

哪种方式为字符串保留内存?

[英]Which way to reserve memory for a string?

I have created a macro to make reserve memory for my strings in C . 我创建了一个宏来为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. 我知道我不应该在生产代码中这样做,因为它将要求每个人都拥有该头文件,并且每个人都必须知道newString是一个宏。

(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). (char*)malloc(sizeof(char) * (size+1))更合适(+1适用于字符串末尾的NULL,如果适用)。

If one is copying a string, strlen() doesn't account for the NULL terminating the string hence an additional memory char is required. 如果要复制字符串,则strlen()不能解释终止字符串的NULL,因此需要额外的存储char

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. 您应该检查分配是否成功。

char* ptr = (char*)malloc(sizeof(char) * size); //Not '+' size!!
if (ptr == 0) //or NULL if defined
{
    //cannot allocate
}

But there is no problem in using a macro 但是使用宏没有问题

The main reason is that sizeof(char) is defined to always be 1. So you should write instead: 主要原因是sizeof(char)始终定义为1。因此,您应该编写:

malloc(size)

and it will be shorter to write this than newString(size) . 并且编写它的时间将比newString(size)短。 Also, malloc returns a void * which you don't need to cast in C. 同样, malloc返回一个void * ,您不需要在C中强制转换。

The other reason is so you don't write a + when you mean * . 另一个原因是,当您表示*时,不要写+

Your macro is equivalent to 您的宏相当于

malloc(size + 1)

as in C you don't need to cast the result of malloc and sizeof(char) equals 1 by definition. 就像在C中一样,您不需要malloc的结果,并且sizeof(char)根据定义等于1 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. 我建议不要这样做,即使在您的个人项目中也是如此,因为我认为这样做没有任何好处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM