0

これは、ファイルとディスクの間のバイトをチェックするために作成したプログラムです。

#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です。今のところ、ファイルとディスクが異なっていても構いませんが、プログラムを動作させたいと思っています。いくつかのデバッグによって、セグメンテーション違反が発生している場所を見つけましたが、その理由はわかりませんでした。

簡単に言えば、なぜこれでセグメンテーション違反が発生するのですか?

前もって感謝します

4

2 に答える 2

2

これらはメモリ内のランダムな場所に書き込んでいます:

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. */
}
于 2014-02-27T15:25:03.553 に答える