简体   繁体   English

C:内存分配-以下结构是否是幼稚的解决方法?

[英]C: Memory allocation - Is the following struct a naive workaround?

I'm currently rolling my own split, trim and other utility string functions in C. While rummaging about SO I've ascertained that functions like strdup() are, in general, considered evil because it allocates memory (unlike other string functions from the same library). 我目前正在用C滚动自己的split,trim和其他实用程序字符串函数。在四处搜寻时,我确定像strdup()这样的函数通常被认为是邪恶的,因为它会分配内存(与其他字符串函数不同)。相同的库)。

However, it seems inevitable that my functions can be written in such a way that they do not allocate memory. 但是,似乎无法避免以不分配内存的方式编写我的函数。 I'm trying to resolve this as best as I can. 我正在尽力解决这个问题。 Currently, I've left all input strings alone (const), and returned a pointer to a new string and documenting that the return must later be free'd. 当前,我将所有输入字符串(const)留空了,并返回了一个指向新字符串的指针,并记录了返回必须稍后释放的情况。

I'm pondering if there is a better way, and this idea struck me. 我正在考虑是否有更好的方法,这个主意打动了我。 I'm trying to figure out if it's actually a good idea or if it's a naive one. 我试图弄清楚这实际上是一个好主意还是天真。 And therein lies my question, is the following solution adviseable? 我的问题就在这里,以下解决方案是否明智? If not, how come? 如果没有,怎么来?

My idea is this, I'll create a struct like so: 我的想法是这样,我将创建一个这样的结构:

typedef struct string {
    char *str;
    bool initialized;
} string;

using it for all my string manipulation work. 用它来完成我所有的字符串操作工作。 At the end of all related functions, just before the return statement I'll call another function, let's call it destroy , on the input string (which wouldn't be a char pointer but the aforementioned struct). 在所有相关函数的结尾,在return语句之前,我将调用另一个函数,在输入字符串上将其称为destroy (不是char指针,而是上述结构)。 That function in turn would check the boolean, ìnitialized , which denotes that memory has been allocated and if so subsequently free it. 该函数依次检查布尔值“ ìnitialized ,它表示已分配内存,如果已分配,则随后释放它。

typedef struct string {
    char *str;
    bool initialized;
} string;

That function in turn would check the boolean, ìnitialized , which denotes that memory has been allocated and if so subsequently free it. 该函数依次检查布尔值“ ìnitialized ,它表示已分配内存,如果已分配,则随后释放它。

You do not need a struct to do that. 您不需要执行此操作的结构。 Initialize with a null pointer any char* pointer that you could have wanted to use your struct for, and you can pass it to free() or realloc() without having to wonder whether or not it has been further assigned. 使用空指针初始化您可能想要使用其结构的任何char*指针,然后可以将其传递给free()realloc()而不必怀疑它是否已被进一步分配。

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

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