看来我列表的第一个节点中有垃圾数据。为什么会这样?
这些是我正在使用的结构的定义。
typedef struct node {
char *x;
struct node *next;
}node;
typedef struct {
struct node *head;
}list;
// create_list()函数:
list* create_list(){
list *myList = malloc(sizeof(myList));
myList->head = NULL;
if (myList->head != NULL){
return NULL;
}
return myList;
}
以下是add_to_list函数的实现
int add_to_list(list* ll, char* item){
node *current = ll->head;
node *new_node = malloc(sizeof(node));
if (!new_node){
fprintf(stderr, "error allocating mem.\n");
return 1;
}
strcpy(new_node->x, item);
new_node->next = NULL;
if(ll->head == NULL){
ll->head = new_node;
return 0;
}else{
while(current->next){
current = current->next;
}
current->next = new_node;
}
return 0;
}
这是print_list();功能
void print_list(list *ll){
node *current = ll->head;
while(current){
printf("%s\t\n",current->x);
current = current->next;
}
}
当我在main.c中调用函数时,我正在这样做:
list *newList = create_list();
char test_var = 'k';
add_to_list(newList, &test_var);
printf("printing whole list : \n");
print_list(newList);
答案 0 :(得分:3)
这是因为您将char作为char指针(即字符串)传递。 变化
char test_var = 'k';
到
char *test_var = "k";
并将通话更改为
add_to_list(newList, &test_var)
到
add_to_list(newList, test_var)
答案 1 :(得分:0)
关于这个陈述:
strcpy(new_node->x, item);
'x'字段是未初始化的指针。所以使用该指针指向目标区域是未定义的行为。
写入未初始化指针指向的位置可能会导致seg错误事件。
AND是数据损坏的原因。你刚刚幸运的一个段错误没有发生,也没有任何其他数据被破坏。
如果您知道数据的最大长度,那么您可以更改结构定义,以便字段'x'是char数组而不是指针。
否则,建议使用类似于:
的内容new_node->x = strdup( data );
if( !new_node->x )
{ // then strdup() failed
perror( "strdup failed" );
// call a cleanup function here
free( new_node );
exit( EXIT_FAILURE );
}
// implied else, strdup successful