0

我有一个关于逻辑错误的问题,错误是

“运行时检查失败 #2 - 变量 'list' 周围的堆栈已损坏。”

in.txt文件一共有60行

这是我的代码:

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

#define FILE_NAME  20
#define LIST_SIZE 50
//void getData(RECORD name[], RECORD score)


typedef struct 
{
    char *name;
    int  score;
}RECORD;


int main (void)
{
    // Declarations
       FILE *fp;
       char fileName[FILE_NAME];
       RECORD list[LIST_SIZE];
       char buffer[100];
       int count = 0;
       int i;
    // Statements
       printf("Enter the file name: ");
       gets(fileName);

       fp = fopen(fileName, "r");

       if(fp == NULL)
      printf("Error cannot open the file!\n");
       while(fgets(buffer, 100, fp) != NULL)
         {  
         list[count].name = (char*) calloc(strlen(buffer), sizeof(RECORD*));
         if(count > 50)
         {

         }

         if( count < 50)
         {
            sscanf(buffer,"%[^,], %d", list[count].name, &list[count].score);
            for( i =1; i < (50 - count); i++)
            {   
                list[count + i].name = 0;
                list[count + i].score = 0;
            }
         }
         count++;

     }

       printf("Read in %d data records\n", count);
       fclose(fp);
       return 0;
}

在这个程序中,我试图将数据从文件读取到结构数组,因此如果数据数量小于 50,则没有数据的结构将归零,如果数据数量超过 50程序只会读取前 50 个结构。

如何修复运行时错误?

4

2 回答 2

0

如果计数 = 50 怎么办?

尝试在您的 while 循环中使用以下内容,将 if 块放在开头或结尾;

if(count >= 50) //count should be checked for >= 50 before being used.
{

}
list[count].name = (char*) calloc(strlen(buffer), sizeof(RECORD*)); //list size is 50 so list[50] won't work. out of bound.
于 2013-04-14T23:49:55.277 回答
0
Perhaps...

while(fgets(buffer, 100, fp) != NULL)
{
  if( count >= 50)
  {
     break;
  }
  if( count < 50)
  {
     list[count].name = (char*) malloc(strlen(buffer)*sizeof(char));
     sscanf(buffer,"%[^,], %d", list[count].name, &list[count].score);
     count++;
  }
}
for( i =0; i < (50 - count); i++)
{   
    list[count + i].name = 0;
    list[count + i].score = 0;
}
于 2013-04-14T23:58:38.577 回答