繁体   English   中英

C中的struct malloc问题

[英]Trouble with struct malloc in C

我目前正在使用C,但无法为此提供解决方案。

编码:

#include <stdlib.h>
#include <string.h>

struct {
   char *name;
   int ID;
   [...]
} example;  

int currentID = 1;

int new_example(char *name){

   char *the_name = malloc(strlen(name) * sizeof(char));
   example *test = malloc(sizeof(example));

   test->name = name;
   test->ID = currentID;
   currentID++;

   [...]

   return test->ID;
}

现在,我知道我必须对该结构的“名称”成员以及该结构本身使用malloc(和free)。 我现在正在做的只是向the_name分配内存,但是test-> name却没有为其分配内存。 所以我想我的问题是,如何将test-> name写入以前分配的内存中? 抱歉,如果我的问题不够清楚,我真的不知道该如何更好地解释它。

提前致谢

你为什么不做这样的事情:

  example *test = malloc(sizeof(example));

  test->name = malloc((strlen(name) + 1) * sizeof(char)); // +1 for null terminator
  test->ID = currentID;

  strcpy(test->name, name);//copy name contents

将指针指向新内存

char *the_name = malloc((strlen(name)+1) * sizeof(char));
example *test = malloc(sizeof(example));

test->name = the_name ;

并将字符串复制到它

strcpy( test->name , name )  ;

注意,您需要为空终止符再分配一个字符:

strlen(name)+1) * sizeof(char)

它看起来应该如下所示:

int new_example(char *name){

   example *test = malloc( sizeof *test ); // or calloc( 1, sizeof *test )
   if ( test ) // you should always check the result of malloc or calloc
   {   
     test->name = calloc( strlen( name ) + 1,   // + 1 for 0 terminator
                          sizeof *test->name );  
     if ( test->name )
     {
       strcpy( test->name, name );
       test->ID = currentID;
       currentID++;

       [...]
       return test->ID;
     }
     else
       free( test );
   }
   return -1; // error indication
}

一些注意事项:

  • 我更喜欢使用sizeof *test不是sizeof ( example ) 如果我更改了test的类型,则不必担心在malloccalloc调用中更改相应的类型。 sizeof *test->name 根据定义, sizeof ( char ) == 1,因此可以将calloc调用写成calloc( strlen( name ) + 1, 1 ) ,但是我仍然喜欢显式的sizeof表达式,以防万一您决定使用wchar作为名称(或其他名称)其他宽字符类型)。

  • calloc将其分配的内存清零。 对于大多数类型而言,这并不重要,但是在为字符串分配空间时我很有意义。

  • 您应该始终检查malloccalloc调用的结果。 如果您不能为test分配内存,则不应尝试为test->name分配内存。 同样,如果您不能为test->name分配内存,则可能表明情况不好,因此您应该退出到目前为止所做的事情。

  • 我假设您正在将test存储在[...]部分中的某些持久性结构中。 如果不是,则存在内存泄漏,因为函数退出时会丢失test指针。

释放对象时,首先要释放name成员,如下所示:

void delete_example( example *ex )
{
  free( ex->name );
  free( ex );
}

不需要将内存分配为一个单独的步骤(但是,如果必须这样做,请记住为终止符'\\0'添加另一个字节)。 使用strdup()直接分配test->name及其新的name副本:

int new_example(char *name){
  example *test = malloc(sizeof(example));

  test->name = strdup(name);
  test->ID = currentID;
  currentID++;

  [...]

  return test->ID;
}

   test->name = strdup(name);

strdup将测量字符串,malloc一些内存,复制该字符串并将malloc的内存返回给您

暂无
暂无

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

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