在链表中插入字符串时出现问题

时间:2015-12-23 16:59:06

标签: c data-structures linked-list

我正在编写一个程序,将数据插入到链表中并打印出来。

LinkedList.c

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

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

void insert(struct node** head_ref,char *new_data)
{
struct node* new_node = (struct node*) malloc(sizeof(struct node));
struct node *last = *head_ref;
strcpy(new_node->data,new_data);
new_node->next = NULL;
if (*head_ref == NULL)
{
   *head_ref = new_node;//assigning head node
   return;
}

while (last->next != NULL)
    last = last->next;//this helps to traverse to last node

last->next = new_node;
return;
}


void printList(struct node *node)//function to print the linked list
{
  while (node != NULL)
  {
   printf(" %s ", node->data);
   node = node->next;
  }
}


int main() {
   int t;
   char datas[1000];
   scanf("%d",&t);
   struct node* head=NULL;
   int i;
   for(i=0;i<t;i++)
   {
      scanf("%s",datas);//this data should be added into the linkedlist
      insert(&head,datas);
   }
   printList(head);

  return 0;
 }

这个程序适用于整数但是如果我使用字符串而不是它显示stdout没有响应 我一直在尝试调试代码更长时间。

2 个答案:

答案 0 :(得分:0)

您的代码提供了未定义的行为。

查看strcpy()的文档。

长话短说,strcpy()要求destination(您的new_node->data)成为已分配的char数组,但您尚未为其分配数据,而您写入未定义(和未分配)的内存。

要克服它,要么为新字符串动态分配空间(并且在发布节点时不要忘记释放空间),要么datachar[]而不是char* {1}}。

此外,请记住buffer overflow weakness。因为它看起来像教育目的代码,只要想一想 - 不要试图解决它,IMO。

答案 1 :(得分:-1)

你错过了内存分配,试试这个:

void insert(struct node** head_ref,char *new_data)
{
struct node* new_node = (struct node*) malloc(sizeof(struct node));
struct node *last = *head_ref;

// you should allocate memory because you use data as char *
new_node->data = malloc(strlen(new_data)+1); 

/* you can use new_node->data = strdup(new_data);  
instead of new_node->data = malloc(strlen(new_data)); and strcpy(new_node->data,new_data); 
because strdup allocate and copy string with exact size */
strcpy(new_node->data,new_data); 

new_node->next = NULL;
if (*head_ref == NULL)
{
   *head_ref = new_node;//assigning head node
   return;
}

while (last->next != NULL)
    last = last->next;//this helps to traverse to last node

last->next = new_node;
return;
}