为什么这个程序会出现分段错误?

时间:2014-02-27 15:22:04

标签: c segmentation-fault disk-io

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

#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的链接。现在,文件和磁盘是否不同并不重要,但我希望我的程序能够运行。通过一些调试,我发现了分段错误发生的地方,但我无法弄清楚原因。

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

提前致谢

2 个答案:

答案 0 :(得分:2)

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

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

因为buff_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. */
}

答案 1 :(得分:1)

更改:

char *buff_device, *buff_file;

char buff_device[1], buff_file[1];
相关问题