0

I first read the file in binary, when I read the end of file, the file is closed, visual stdio 2013 error pointer over the border.

FILE *fp;
fp = fopen("stu_manage.txt", "ab+");
fseek(fp,0L,SEEK_END);
long last = ftell(fp) / length;
long i = 0L;
rewind(fp);
struct student *node=(struct student*)malloc(sizeof(struct student));
for (; i < last; i++)
{
    if (fread(&node[i], length, 1, fp) != 1)
    {
        printf("read conpletely");
        break;
    }
}
if (fp!=NULL)
   fclose(fp);

When I put here the pointer change into global variables, this error is solved, the array in some degree equivalent to the pointer here could not run I feel unable to understand.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
qiabigin
  • 45
  • 7

2 Answers2

3

In your code, you're allocating memory for only one variable of type struct student in node, but you're accessing out-of-bound memory by using the incremental index i in

if (fread(&node[i], length, 1, fp) != 1)

which in turn invokes undefined behaviour.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

I think the problem is in the line

if (fread(&node[i], length, 1, fp) != 1)

Because fread will return > 0 value when it is successful. If the struct student has size > 1 your loop will break after the first node has been read. And it will not read remaining nodes

Yasir Majeed
  • 739
  • 3
  • 12