【问题标题】:When the file pointer reads the file over the border?当文件指针越界读取文件时?
【发布时间】:2015-04-01 09:06:43
【问题描述】:

我首先以二进制读取文件,当我读取文件末尾时,文件关闭,视觉stdio 2013错误指针越界。

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);

当我把这里的指针改成全局变量后,这个错误就解决了,数组在某种程度上相当于这里的指针无法运行我感觉无法理解。

【问题讨论】:

  • 标准警告:请do not castmalloc()C 中的家人的返回值。
  • 什么是length?它是在哪里定义的?
  • @SouravGhosh:总而言之,你不要在任何时候强制转换malloc()的返回值,因为:在C中​​是不需要的;在 C++ 中它是必需的,但在 C++ 中你甚至不使用 malloc() ;)
  • @Zaibis 是的。对。 :-)

标签: c file pointers


【解决方案1】:

在您的代码中,您只为node 中的一个struct student 类型的变量分配内存,但您正在使用增量索引i 访问越界内存

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

依次调用undefined behaviour

【讨论】:

    【解决方案2】:

    我认为问题出在这条线上

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

    因为 fread 成功时会返回 > 0 的值。如果 struct student 的 size > 1 你的循环将在第一个节点被读取后中断。而且它不会读取剩余的节点

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-26
      相关资源
      最近更新 更多