gpt4 book ai didi

c - 当我尝试向链接列表添加新节点时,为什么会出现段错误?

转载 作者:行者123 更新时间:2023-11-30 15:44:45 25 4
gpt4 key购买 nike

只是想弄清楚为什么这段代码返回段错误。 Gdb 说给我错误的行 strcpy(newNode -> data -> Ticket_name, name); 它在函数 strcat() 中说。有任何想法吗?我还想指出,我对 C 还很陌生。

void add_ticket(tm_type * tm)
{
char name[TICKET_NAME_LEN+1], type, zone[TICKET_ZONE_LEN], buffer[5], *ptr, *pos;
int price;
BOOLEAN check = TRUE;
printf("Add Ticket\n");
printf("----------\n");
printf("\n");
printf("Ticket name (1-40 characters): ");
if(fgets(name, sizeof(name), stdin) != NULL){
if(name[0] != '\n'){
if((pos=strchr(name, '\n')) != NULL){
*pos = '\0';
}

printf("\nTicket type (1 character): ");
type = fgetc(stdin);
if(type != '\n'){

read_rest_of_line();
printf("\nTicket zone (1-3 characters): ");
if(fgets(zone, sizeof(zone), stdin) != NULL){
if(zone[0] != '\n'){
if((pos=strchr(zone, '\n')) != NULL){
*pos = '\0';
}

printf("\n\n");
printf("Price (in cents): ");
if(fgets(buffer, sizeof(buffer), stdin) != NULL){
price = strtol(buffer, &ptr, 10);
if(buffer[0] != '\n'){

//create new node
stock_node *newNode = (stock_node*)malloc(sizeof(stock_node));

if(newNode == NULL){
fprintf(stderr, "Unable to allocate memory for new ticket.\n");
exit(EXIT_FAILURE);
}

strcpy(newNode -> data -> ticket_name, name);
newNode -> data -> ticket_type = type;
strcpy(newNode -> data -> ticket_zone, zone);
newNode -> data -> ticket_price = price;
newNode -> data -> stock_level = DEFAULT_STOCK_LEVEL;
newNode -> next_node = NULL;

//check for first insertion
if(tm -> stock -> head_stock -> next_node == NULL){
tm -> stock -> head_stock -> next_node = newNode;
printf("First ticket added.\n");
}

else{
//else loop through the list and find the last
//node, insert next to it
stock_node *stream = tm -> stock -> head_stock;
while(check == TRUE){

if(stream -> next_node == NULL){
stream -> next_node = newNode;
printf("Ticket added.\n");
check = FALSE;
}
stream = stream -> next_node;
}
}
}
}
}
}
}
}
}
}

最佳答案

您为newNode分配了空间,但从未进行过任何类型的初始化。由于此 newNode -> data 包含垃圾,因此当您使用第二个箭头取消引用它时,您会遇到段错误。我的c生锈了,但我相信你想要

// create new node
stock_node *newNode = (stock_node*)malloc(sizeof(stock_node));

newNode -> data = (data_struct*)malloc(sizeof(data_struct));

...

关于c - 当我尝试向链接列表添加新节点时,为什么会出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19342484/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com