运行我的C程序时在Linux中出现分段错误

ash*_*bhy 1 c linux simulation

我试图在Red Hat Linux中模拟cat命令.我运行程序时出现分段错误.

例如:

./a.out a > b
Run Code Online (Sandbox Code Playgroud)

a包含你好.我希望你好被复制b.

我的代码如下:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

int main(int argc,char *argv[])
{
    int f, fd, r;
    char buf[100];

    if (argc < 2)
    {
        printf("Error");
        return 0;
    }
    else
    {
        if (!strcmp(argv[2],">"))
        {
            f = open(argv[1],0,00777);

            if (f == -1)
                printf("no file");
            else
            {
                fd = creat(argv[3],00777);
                while( (r = read(f,buf,50)) > 0)
                    write(fd, buf, r);
            }
        }
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

为什么我会收到分段错误?

我有一个类似的程序,我打开并以相同的方式创建文件,该程序正在运行,但这个给我一个分段错误.

Som*_*ude 6

这可能是因为重定向是由shell处理的,而不是由你的程序处理的,所以argv[2]NULLargv[3]不存在.

但是,您应该使用调试器来查找实际发生的情况.然后添加适当的错误检查.

  • 知道标准的+1表示`argv [argc]`保证为NULL(你可能不会惊讶地发现它经常被解释为未定义). (4认同)
  • @ashwinbhy然后它可能正在工作,因为它是_similar_.重定向和管道由shell处理_always_. (2认同)