【问题标题】:Why does the following code raise a SegFault. c(Linux)为什么以下代码会引发 SegFault。 c(Linux)
【发布时间】:2010-09-05 19:40:24
【问题描述】:

此代码将反转文档的数据并将其保存在同一文档本身中。 但是我遇到了分段错误。请帮忙,我不知道为什么会出现分段错误。

#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>


int main (int argc,char* argv[])
{

    int fd,n,i,j;

    char* buf;

    if(argc<2)
    printf("USAGE: %s file-to-reverse.\n",argv[0]);

    fd=open(argv[1], O_RDWR);
    if(fd==-1)
    printf("ERROR: Cannot reverse %s,file does not exist.\n",argv[1]);

    i = 0;
    j = n-1;

    while(i < j)
    {   
        read(fd,buf,n);

        char ib = buf[i];
        char jb = buf[j];

        jb = i++;
        ib = j--;

        write(fd,buf,n);
    }

    free(buf);
    close(fd);
}

EDIT1 我尝试添加:

#include <sys/stat.h>
struct stat fs;


  fstat(fd, &fs);
  n= fs.st_size;
  buf = malloc(n * sizeof (char));

但现在它只是一次又一次地复制文档中的字符,而不是 反转它们。

【问题讨论】:

  • 除了答案之外,“n”未在“j = n-1;”行初始化。

标签: c linux ubuntu segmentation-fault file-descriptor


【解决方案1】:

你不分配,也不初始化buf。

【讨论】:

    【解决方案2】:

    你从未初始化过n,所以它可能是任何东西,甚至是负数。使用fstat 或其他方法确定文件的大小并将其存储在n 中。

    【讨论】:

      【解决方案3】:

      您的缓冲区未分配且 n = 0,因此您将尝试读取 0 个字符。 这应该可以修复您的代码:

      buf = malloc(10 * sizeof (char));
      n = 10;
      

      资源:

      【讨论】:

        【解决方案4】:

        关于你的第二次编辑 - 你的循环是错误的。

        (1) 将读取和写入从循环中取出 - 这就是它不断重复写入的原因。

        (2) 你需要回到文件的开头,否则你只会将新数据附加到文件的末尾。

        (3) 实际上,您必须先反转缓冲区中的字符,然后再将它们写出。

        read(fd, buf, n);
        
        while (i < j)
        {
        
            char t = buf[i];
        
            buf[i] = buf[j];
        
            buf[j] = t;
        
            i++;
            j--;
        }
        
        lseek(fd, 0, SEEK_SET);
        
        write(fd, buf, n);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-02-25
          • 1970-01-01
          • 1970-01-01
          • 2016-06-21
          • 1970-01-01
          • 2020-03-25
          • 1970-01-01
          相关资源
          最近更新 更多