繁体   English   中英

如何正确分配具有char *字段的struct *

[英]How to properly allocate struct* that has char* field

我正在使用malloc为head结构分配指针,但我希望'title'字段的大小为100个char元素。 如何正确地做到这一点?

struct tail{
    int x;
};

struct head{
    char *title;
    struct tail *next;
};

void function(){
    struct head *h;
    //this (program won't know how much to allocate for 'title':
    h = (struct head*)malloc(sizeof(struct head));

    //VS this (Segmentation fault (core dumped)):
    h->title = (char*)malloc(sizeof(char)*255);
    h->next = (struct tail*)malloc(sizeof(struct tail*));

    /*
    or maybe I should alloc h, then realloc title?
    If that's the answer, how will I free whole structure later?
    */
}

PS。 我故意不使用char title[100]

编辑说明。 (char)是一个拼写错误,我的代码中有(char *)

你在编译-wall吗?

如果你看一下这个警告就应该得到

so.c:16:16: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]

malloc的返回值是一个void指针,它指向你正在分配的内存块 - 你将内存的地址转换为char ,这是因为你错过了指针声明*从而截断了实际的地址,然后导致你的段错误。

C确实知道从一开始就为struct分配多少内存,因为指针有一个固定的大小,这就是你在头/尾结构上做malloc时所分配的全部内容。

为什么不使用第一种方式,然后为title分配空间?

h = malloc(sizeof(struct head));
h -> title = malloc(sizeof(char) * 100);
h -> next = malloc(sizeof(struct tail*));

诀窍是要记住, title是一个char *因此,所有你需要的h是一个指针,而不是实际的数组空间。

您只需使用以下命令即可释放:

free(h -> title);
free(h -> next);
free(h);

你的第二种方法的问题是没有分配h ,所以它是segfaulted。 另外,你将malloc的结果(一个void * )转换为一个char ,这实际上没有意义 - 我认为你的意思是要转换为char * ,无论如何都不需要,因为C可以转换为void *自动。

你可以做一些像创建一个创建具有给定标题大小的结构头的函数。 请记住,您还必须(应该)创建一个free_head函数,该函数能够销毁由下面的create_head函数创建的对象。

struct head* create_head( unsigned title_size) {
     struct tail* t = malloc (sizof(struct tail) );
     if ( ! tail ){
         return NULL;
     }
     char* title = malloc ( title_size * sizeof(char) );
     if ( !title ){
          free(t)
          return NULL;
     }
     struct head* h = malloc (sizeof (struct head) );
     if ( !head ){
         free (t);
         free (title);
         return NULL;
     }
     head->title = title;
     head->next = t;
     return head;
}

现在你可以简单地使用如下函数:

struct head* = create_head(100);

然后当然你需要写一些代码来正确地破坏结构头,否则你会创建一个内存泄漏。 还要记住,此函数不会为终止'\\ 0'字节分配一个额外的字符。 终止C字符串

更迭!

暂无
暂无

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

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