[英]segmentation fault when using argv[1]
when i try to run this program with : ./prog_name eventCNT i confront with segmentation fault error while with other argument everything is ok...当我尝试使用以下命令运行此程序时:./prog_name eventCNT 我遇到分段错误错误,而其他参数则一切正常...
int main(int argc, char *argv[]) {
printf("Application for up/down/random counter on 7 seg display\n");
if ( (strcmp(argv[1], "eventCNT") == 0 && argc != 2) || (strcmp(argv[1], "eventCNT") != 0 && argc != 3) )
{
printf( "usage: %s <direction or event counting> <delay>\n", argv[0] );
printf( "valid direction : up, down, updown, random\n");
printf( "valid event counting : eventCNT\n");
printf ("recommended delay range in ms : 0 to 1000\n");
}
else
{
.
.
.
}
}
You should check argc
before accessing argv
您应该在访问
argv
之前检查argc
If argc == 1
and you are accessing argv[1]
first, you are accessing invalid memory because argv
only has one member, which is argv[0]
如果
argc == 1
并且您首先访问argv[1]
,则您正在访问无效内存,因为argv
只有一个成员,即argv[0]
C++ evaluates statements from left to right, therefore having undefined behaviour first and then checking whether it was ok to do this is not the best way. C++ 从左到右评估语句,因此首先具有未定义的行为然后检查是否可以这样做并不是最好的方法。 Invert the checks to
argc
and argv
将检查反转为
argc
和argv
Actually you should write code in a more defensive way like实际上,您应该以更具防御性的方式编写代码,例如
if (argc < 2)
{
// Error, not enough arguments
return -1
}
// From here you know that argv[1] will be a valid string to something and you can freely get `argv[1]`
You should use你应该使用
if (argc >= 2 && strcmp(argv[1], "eventCNT") == 0)
not不是
if (strcmp(argv[1], "eventCNT") == 0 && argc != 2)
Because if arguments are less than 2, argv[1]
is not defined, will point to a random memory address.因为如果arguments小于2,
argv[1]
没有定义,会指向一个随机的内存地址。 Therefore a segmentation fault occurs.因此出现分段错误。
Also strcmp
has undefined behavior if you points to something not a null-terminated string.如果您指向的不是以空字符结尾的字符串,那么
strcmp
也有未定义的行为。 see strcmp here在这里看到strcmp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.