为什么该程序会产生分段错误?

vfsoraki

这是我编写的用于检查文件和磁盘之间的字节的程序。

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

#define BYTES_TO_READ 64

int main(int argc, char **argv)
{
  int device = open("/dev/sdz", O_RDWR);
  if(device < 0)
  {
      printf("Device opening error\n");
      return 1;
  }
  int file = open("test.txt", O_RDONLY);
  if(file < 0)
  {
      printf("File opening error\n");
      return 2;
  }
  int byte, device_loc, file_loc;
  char *buff_device, *buff_file;
  for(byte = 0; byte<BYTES_TO_READ; byte++)
  {
      device_loc = lseek(device, byte, SEEK_SET); /* SEG FAULT */
      file_loc = lseek(file, byte, SEEK_SET);
      printf("File location\t%d",file_loc);
      printf("Device location\t%d",device_loc);
      read(device, buff_device, 1);
      read(file, buff_file, 1);
      if( (*buff_device) == (*buff_file) )
      {
          printf("Byte %d same", byte);
      }
      else
      {
          printf("Bytes %d differ: device\t%d\tfile\t%d\n",byte, *buff_device, *buff_file);
      }
  }
  return 0;
}

请不要问为什么我要比较sdz文件。这正是我想要做的:将文件直接写到磁盘上并读回。

sdz是回送设备,带有的链接/dev/loop0现在,文件和磁盘是否不同并不重要,但我希望程序能够正常工作。通过一些调试,我发现了分段错误发生的位置,但是我不知道为什么。

长话短说:为什么这会给我带来细分错误?

提前致谢

j

这些正在写入内存中的随机位置:

read(device, buff_device, 1);
read(file, buff_file, 1);

asbuff_devicebuff_file是未初始化的指针。使用char类型并传递其地址。

char buff_device;
char buff_file;

/* Check return value of read before using variables. */
if (1 == read(device, &buff_device, 1) &&
    1 == read(file, &buff_file, 1))
{
    if (buff_device == buff_file)
    /* snip */
}
else
{
    /* Report read failure. */
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章