ANSI C -程序接收信号SIGSEGV,分段故障

yk9xbfzb  于 2023-03-29  发布在  其他
关注(0)|答案(1)|浏览(153)

我使用的是ANSI C,当我运行下面的代码时,得到了“程序接收信号SIGSEGV,分段错误。”编译正常。没有错误。

#define MAX_LINE_SIZE 1024
#define DELIMITER ","
#define TICKET_NAME_LEN 40
#define TICKET_ZONE_LEN 10

struct stock_data 
{
    char ticket_name[TICKET_NAME_LEN+1];
    char ticket_type;
    char ticket_zone[TICKET_ZONE_LEN+1];
    unsigned int ticket_price;
    unsigned int stock_level;
};

typedef struct stock_node 
{
    struct stock_data * data;
    struct stock_node * next_node;
} stock_node;

char temp_line[MAX_LINE_SIZE];
char *token;
int i, count = 0;

stock_node * snode = NULL;
struct stock_data * sdata = NULL;

FILE *stock_file = fopen( stockfile, "r" );

while (fgets(temp_line, MAX_LINE_SIZE, stock_file) != NULL) {

  token = strtok (temp_line, DELIMITER);
  count++;

  snode = (stock_node *) realloc(snode, count * sizeof(stock_node));
  if (snode == NULL) { abort(); }  

  snode->data = (struct stock_data *) malloc(sizeof(struct stock_data));
  if (snode->data == NULL) { abort(); }  

  i = 1;

 while(token != NULL) {
     switch(i) {
        case 1:
           strcpy(snode[count - 1].data->ticket_name, token);
           break;
        case 2:
           snode[count - 1].data->ticket_type = token[0];
           break;
        case 3:
           strcpy(snode[count - 1].data->ticket_zone, token);
           break;
        case 4:
           snode[count - 1].data->ticket_price = atoi(token);
           break;
        case 5:
           snode[count - 1].data->stock_level = atoi(token);
           break;                                                            
     }

     token = strtok (NULL, DELIMITER);
     i++;
  }
}

我用gdb工具调试了一下,发现下面几行出错:(对于其中的任何一个。我尝试逐个禁用它们,每个都导致了Segfault错误。)

**strcpy(snode[count - 1].data-〉ticket_name,token);

ticket_type = token[0];
strcpy(snode[count - 1].data-〉ticket_zone,token);
sNode[count - 1].data-〉ticket_price = atoi(token);
sNode[count - 1].data-〉stock_level = atoi(token);**

6ss1mwsb

6ss1mwsb1#

看起来snode[count - 1].data从未被初始化。只有第一个索引snode[0].data被分配
我觉得你应该换掉

snode->data = (struct stock_data *) malloc(sizeof(struct stock_data));
if (snode->data == NULL) { abort(); }

作者

snode[count - 1].data = (struct stock_data *) calloc(1, sizeof(struct stock_data));
if (snode[count - 1].data == NULL) { abort(); }

相关问题