简体   繁体   English

结构中变量的动态分配

[英]dynamic allocation for variable in struct

I'm trying to figure out where my problem is and can't seem to find it, I want to a allocate dynamic memory to a variable within a struct, I have tried in all sorts of ways and it just does not work I get a warning: Exception has occurred.我试图找出我的问题出在哪里,但似乎找不到,我想将动态 memory 分配给结构中的变量,我尝试了各种方法,但它只是不起作用我得到警告:发生异常。 segmentation fault分段故障

When I allocate memory to the * bookcase its works but when i try to allocate to a variable within the structure i get the warning.当我将 memory 分配给 *书柜时,它的工作原理但是当我尝试分配给结构内的变量时,我得到了警告。

example of what I was trying to do我试图做的例子

struct book
 {
  int num;
  char* book_name;
 }*bookcase;

void addbook(void)
 {
  char buff[20];
  gets(buff);
  bookcase->book_name = ( char *)malloc(strlen(buff));
  strcpy(bookcase->book_name,buff);
 }

Sorry for the question feels really stupid, unfortunately i could not understand the problem, Any help would be appreciated.抱歉这个问题感觉很愚蠢,不幸的是我无法理解这个问题,任何帮助将不胜感激。 Thank you.谢谢你。

You're not allocating enough memory.您没有分配足够的 memory。

A string in C is terminated by a null byte. C 中的字符串由 null 字节终止。 The amount of space you're allocating doesn't account for that null byte, so you write past the end of allocated memory when you copy the string.您分配的空间量不考虑该 null 字节,因此您在复制字符串时写入已分配 memory 的末尾。 This triggers undefined behavior which in this case causes a crash.这会触发未定义的行为,在这种情况下会导致崩溃。

Add space for the null byte when allocating:分配时为 null 字节添加空间:

bookcase->book_name = malloc(strlen(buff) + 1);
strcpy(bookcase->book_name,buff);

Or, if your system supports it, use strdup which does the allocation and copy in one step:或者,如果您的系统支持它,请使用strdup一步完成分配和复制:

bookcase->book_name = strdup(buff);
  1. you need to allocate memory for the struct itself您需要为结构本身分配 memory
bookcase = malloc(sizeof(*bookcase));

then you need to allocate enough memory for the title.那么你需要为标题分配足够的 memory。 You do not allocate enough as string in C is terminated by the bull character and this nill char is not counted by the strlen您没有分配足够的字符串,因为 C 中的字符串由公牛字符终止,并且strlen不计算此 nill 字符

bookcase -> book_name = malloc(strlen(buff) + 1);

But you do not two allocations for that.但是你不要为此分配两次。

struct book
 {
  int num;
  char book_name[];
 };

struct book *addbook(void)
 {
  char buff[20];
  struct book *bookcase;
  fgets(buff, sizeof(buff), stdin); 
  /* you should check for errors in all I/O operations and memory allocations */
  bookcase = malloc(sizeof(*bookcase) + strlen(buff) + 1);
  strcpy(bookcase->book_name,buff);
  return bookcase;
 }

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

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