[英]Getting segmentation fault in Linux when running my C program
I am trying to simulate the cat command in Red Hat Linux . 我正在尝试在Red Hat Linux中模拟cat命令。 I am getting a segmentation fault when I run my program.
运行程序时出现分段错误 。
For example: 例如:
./a.out a > b
a
contains hello. a
包含你好。 I expect hello to be copied in b
. 我希望你好会被复制到
b
。
My code is as follows: 我的代码如下:
#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;
}
Why am I getting a segmentaion error? 为什么会出现细分错误?
I have a similar program where I open and create the file in the same manner, and that program is running, but this one is giving me a segmentation fault. 我有一个类似的程序,该程序以相同的方式打开和创建文件,并且该程序正在运行,但是这给了我一个分段错误。
It's probably because the redirection is handled by the shell and not by your program, so argv[2]
is NULL
and argv[3]
does not exist. 可能是因为重定向是由Shell处理的,而不是由程序处理的,因此
argv[2]
为NULL
而argv[3]
不存在。
However you should use a debugger to find out what is really happening. 但是,您应该使用调试器来了解实际情况。 And then add proper error checking.
然后添加适当的错误检查。
You can live without gdb
here - but you have to start solving the problem in a structured manner: 您可以在这里没有
gdb
生活-但您必须以结构化的方式开始解决问题:
Don't take anything as granted. 不要理所当然。 Eg, even if you call your program as
program > file
, don't assume that argv
looks the way you assume, but check it by outputting each of them: 例如,即使您以
program > file
调用程序,也不要假设argv
看起来像您假设的样子,而是通过输出每个参数来检查它:
printf("argc: %d\\n", argc); printf("argv[0]: %s\\n", argv[0]); printf("argv[1]: %s\\n", argv[1]); printf("argv[2]: %s\\n", argv[2]); printf("argv[3]: %s\\n", argv[3]); // the se can be expressed better with a for loop - but I'll leave that as an exercise for you
Only take things as granted what you have verified: if you know that argc >= 2
, don't access argv[2]
and/or argv[3]
. 只接受您已经验证的事情:如果您知道
argc >= 2
,请不要访问argv[2]
和/或argv[3]
。
Don't say 不要说
if(argc<2) { printf("Error"); return 0; }
but 但
if(argc<2) // according to the point before, better y3 or <4 { printf("Too few command line arguments"); return 1; // not 0; 0 would mean success }
Joachim Pileborg's answer is obviously correct, just try to run your program as 约阿希姆·皮勒伯格(Joachim Pileborg)的答案显然是正确的,只要尝试以
./a.out a \> b
to prevent the shell from interpreting ">" as a redirection. 防止外壳程序将“>”解释为重定向。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.