简体   繁体   中英

Segmentation Fault with string compare

When working with a basic example like this, I am getting a segmentation fault. I believe it's due to the size of the data not being fixed. How can I have variable length data attached to a struct?

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;
}

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

Answer is - No , you cannot. The reason is the size of the struct should be known at compile time.

The reason for segmentation fault is, your program is accessing head pointer before allocating memory to it:

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

Allocate memory before using head :

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

Make sure to free allocated memory once you have done with it.


There is something known as Flexible Array Member(FAM) introduced in C99 standard. It may be of your interest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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