C语言 什么是分段错误(核心转储)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19641597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
what is Segmentation fault (core dumped)?
提问by user2929110
I am trying to write a C program in linux that having sqrt of the argument, Here's the code:
我正在尝试在 linux 中编写一个具有参数 sqrt 的 C 程序,这是代码:
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
int main(char *argv[]){
float k;
printf("this is consumer\n");
k=(float)sqrt(atoi(argv[1]));
printf("%s\n",k);
return 0;
}
After I type in my input at the "shell> " prompt, gcc gives me the following error:
在“shell>”提示符下输入我的输入后,gcc 给了我以下错误:
Segmentation fault (core dumped)
回答by Eric Finn
"Segmentation fault" means that you tried to access memory that you do not have access to.
“分段错误”意味着您尝试访问您无权访问的内存。
The first problem is with your arguments of main. The mainfunction should be int main(int argc, char *argv[]), and you should check that argcis at least 2 before accessing argv[1].
第一个问题是你的论点main。该main函数应该是int main(int argc, char *argv[]),并且您应该argc在访问之前检查它至少为 2 argv[1]。
Also, since you're passing in a floatto printf(which, by the way, gets converted to a doublewhen passing to printf), you should use the %fformat specifier. The %sformat specifier is for strings ('\0'-terminated character arrays).
此外,由于您传入的是floatto printf(顺便说一下,double在传递到 时会转换为 a printf),因此您应该使用%f格式说明符。该%s格式说明为字符串('\0'封端的字符数组)。

