[英]SIGSEGV memory access violation
I am writing a school project in C and apparently something in this code is causing it to crash with SIGSEGV memory access violation error even though it compiles without any problems. 我正在用C语言编写一个学校项目,显然,此代码中的某些内容导致它因SIGSEGV内存访问冲突错误而崩溃,即使它编译时没有任何问题。
int P, H, S, R;
char *end;
if (argc != 5){
printf("Incorrect ammount of parameters.\n");
exit(1);
}
errno = 0;
P=strtod(argv[2],&end);
H=strtod(argv[3],&end);
S=strtod(argv[4],&end);
R=strtod(argv[5],&end);
if (errno != 0){
printf("Wrong input: %s\n",strerror(errno));
exit(1);
}
//I know have only integers in P,H,S,R, that's why I can afford to do the following. Please don't judge me.
if ((H < 0) || (S < 0) || (R < 0) || (H > 5000) || ( S > 5000) || ( R > 5000)){
printf("Incorrect waiting time H,S,R >= 0 && H,S,R < 5001\n");
exit(1);
}
if ((P < 1) || ((P % 2)==1)){
printf("Must be even number bigger than 0.");
exit(1);
}
Any ideas? 有任何想法吗? EDIT: even if I put printf at the very beginning of the code i does not print anything, only memory access violation error which looks like this
编辑:即使我将printf放在代码的开头,我也不打印任何内容,仅出现如下所示的内存访问冲突错误
Neoprávněný přístup do paměti (SIGSEGV) (core dumped [obraz paměti uložen])
It would be best if you could track down the exact line where the error is occurring. 最好是,您可以跟踪发生错误的确切行。 You can do that in a debugger, or simply by putting
printf
statements all over the place and seeing what the last one that works is. 您可以在调试器中执行此操作,也可以直接在各处放置
printf
语句并查看最后一个有效的语句。
However, from a quick look, I think that the problem is here: 但是,从快速的角度来看,我认为问题出在这里:
R=strtod(argv[5],&end);
SIGSEGV (segmentation fault) means that you attempted an invalid memory access. SIGSEGV(分段错误)表示您尝试了无效的内存访问。 A few lines up, you checked that
argc == 5
. 几行后,您检查了
argc == 5
。 This means that the valid indices for argv
are 0 through 4. There is no argv[5]
, and any attempt to read it results in undefined behaviour. 这意味着
argv
的有效索引是0到4。没有argv[5]
,任何尝试读取它的操作都会导致未定义的行为。
The problem is here: 问题在这里:
if (argc != 5)
…
R=strtod(argv[5],&end);
When argc == 5
, argv[5] == NULL
. 当
argc == 5
, argv[5] == NULL
。 You crash when you convert a null pointer. 转换空指针时会崩溃。 You should be using
strtod()
on argv[1]
through argv[4]
. 您应该在
argv[1]
到argv[4]
上使用strtod()
。 It is unusual to use strtod()
to convert strings to integers; 使用
strtod()
将字符串转换为整数是不寻常的。 usually, you'd use strtol()
or one of its relatives. 通常,您将使用
strtol()
或其亲戚之一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.