繁体   English   中英

使用包含多个元素的结构的malloc

[英]Use of malloc of a struct containing multiple elements

我在这里做错了什么?

我有一个QueueElement结构,其中包含char *文本和指向下一个元素的指针,因此很显然是一个链表:

//QElement as in QueueElement
struct QElement {
    char* text;
    struct QElement* next;
};
typedef struct QElement QElement;

....

void enqueue (char* string){
QElement *new = (QElement *)malloc(sizeof(QElement)); 
//QElement cast is probably redundant but it doesn't hurt anyone
strcpy (new->text, string);

//some other stuff happening here, linking to other element in linked list, 
//but thats not of interest at the moment

}

....

如果尝试在主函数中加入一个单词,则会不断出现分段错误,并且valgrind会告诉我,当我使用strcpy时我做错了什么,因此我的malloc似乎不正确。 我该怎么做?

在这段代码中

strcpy (new->text, string);

new->text未分配内存。 它可能包含一些垃圾值,或者一些写保护的内存地址,甚至是NULL。 将该指针传递给strcpy()会导致您出现未定义的行为,并且作为副作用,您可能会遇到分段错误。

您可以使用strdup()或可以在将strcpy()指向该指针之前将内存分配给new->text 两种情况下,您都需要在以后free()已分配的内存。

也,

  1. 不要 malloc()的返回值。
  2. 使用指针之前,请检查动态内存分配[ malloc() / calloc() ]是否成功。

其他答案推荐的strdup(.)是非标准的。 如果您不在Unix平台上,则可能无法使用。

但是,这一点是正确的。 您需要分配内存来存储您的字符串。

尝试:

const size_t sz=(strlen(string)+1)*sizeof(*string);//Space required. Including '\0' terminator.
new->text=malloc(sz);//space allocated.
if(new->text==NULL){//sz never 0 because +1.
   exit(EXIT_FAILURE);//Allocation failed in non-error handled function.
}
memcpy(new->text,string,sz); //typically fastest way to copy!

代替strdup(.)

实际上,我不需要使用sizeof(*string) (因为它始终为1),但是编译器会发现这一点,这只是一个好习惯。

有一天,世界将更加统一地迁移到多字节字符,并且这段代码已经为光荣的黎明做好了准备!

完成“ QElement”操作后,不要忘记free(.) 您可能应该编写这样的函数:

void QElementDestroy(QElement*const element){
    if(element==NULL){
        return;//Nothing to do!
    }
    free(element->text);//Needs NULL protection.
    free(element);//Does not need NULL protection. But we've done the test anyway!
    //NB: Order matters here. A lot.
}

并在完成enqueue(.)返回的值后调用它。

如果您希望字符串“不活跃”,则在调用destroy之前将元素设置为element->text=NULL free(NULL)是不执行任何操作并正常返回的要求。

PS:我认为strdup(.)有点n00b陷阱。 他们花了一些时间才能匹配malloc(.)free(.)strdup(.)有点叛徒,因为其他str...函数都没有分配调用者期望free(.)空间free(.) 这也是非标准的。

因为您只为结构变量分配内存。 您必须在结构成员中分配内存。

 new->text=malloc(10);//for example 

分配内存后,可以使用strcpy函数。

您已为new分配了内存,但没有为text成员变量分配内存。 text分配内存并执行代码。

暂无
暂无

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

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