【发布时间】:2014-11-14 15:09:34
【问题描述】:
----------
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
char *val;
struct node *next;
};
void add_to_list(struct node **, char *);
void list_all_elements(struct node *);
int main (int argc, char **argv)
{
char *val;
struct node *head = NULL;
do {
scanf("%s",val);
add_to_list(&head, val);
}
while(val[0] != '\\');
list_all_elements(head);
}
void add_to_list(struct node **head, char *val)
{
//This produces a segfault
struct node *temp = malloc(sizeof *temp);
//EDIT - Fixed as per comments
temp->val = malloc(strlen(val) + 1);
strcpy(temp->val, val);
temp->next = NULL;
if(head!=NULL)
temp->next = *head;
*head = temp;
}
void list_all_elements(struct node *head)
{
while(head!=NULL) {
printf("%s\n",head->val);
head = head->next;
}
}
这就是我为实现链表而编译的。现在,由于某种原因 malloc'ing 会产生分段错误。
可以肯定的是,我将 char * 替换为 char [] 并且代码运行良好。 malloc 是否因此而出错,或者是否有一些我似乎无法找到的微不足道的错误?
【问题讨论】:
-
head 不会为空,您应该检查 *head,但这不会改变任何东西,这意味着每次分配 temp->next = *head;这是正确的做法,你根本不需要 if (和 temp->next = NULL)
-
1)
char *val;-->char val[MAX_STRING_SIZE];
标签: c string pointers linked-list