【问题标题】:Segmentation Fault with string compare字符串比较的分段错误
【发布时间】:2018-01-27 20:59:34
【问题描述】:

在使用这样的基本示例时,我遇到了分段错误。我相信这是由于数据的大小没有固定。如何将可变长度数据附加到结构?

struct Node {
    char * data;
    struct Node* next;
};

void compareWord(struct Node** head_ref, char * new_data) {
  if (strcmp((*head_ref)->data, new_data) > 0) {
      head_ref->data = new_data;
  }
}

int main(int argc, char* argv[]) {
  struct Node* head = NULL;
  head->data = "abc";
  char buf[] = "hello";
  compareWord(&head, buf);
  return 0;
}

【问题讨论】:

  • 你没有显示printWord功能,请发minimal reproducible example
  • Home 有多少内存分配给head,然后再尝试使用它?? (提示,它是一个初始化的指针NULL...如果您在为其分配内存之前尝试使用它,则保证会出现段错误)
  • @OldProgrammer 错字已修复

标签: c struct segmentation-fault


【解决方案1】:

How can I have variable length data attached to a struct?

答案是 - ,你不能。原因是结构体的大小应该在编译时就知道了。

分段错误的原因是,你的程序在分配内存之前访问了head指针:

  struct Node* head = NULL;
  head->data = "abc";

在使用head之前分配内存:

  struct Node* head = NULL;
  head = malloc (sizeof(struct Node));
  if (NULL == head)
      exit(EXIT_FAILURE);
  head->data = "abc";

确保在完成后释放分配的内存。


在 C99 标准中引入了称为 Flexible Array Member(FAM) 的东西。您可能感兴趣。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-28
    • 2017-08-23
    • 1970-01-01
    • 2013-12-08
    • 2022-11-18
    • 2013-09-20
    • 1970-01-01
    相关资源
    最近更新 更多