[英]Segmentation fault while using atoi()
I'm getting a segmentation fault (core dumped) error when I try to run my program.当我尝试运行我的程序时遇到分段错误(核心转储)错误。 I pass this into the command line./stats 1 2 50 100 argv[3] is the number of samples, and argv[4], argv[5] are the lower and upper bounds of the sample.我把这个传入命令行。/stats 1 2 50 100 argv[3] 是样本数,argv[4], argv[5] 是样本的下限和上限。 I'm going through it slowly to see where I get errors and I think I get seg fault when I try to assigned these to int variables我正在慢慢地检查它以查看我在哪里出错,我想当我尝试将它们分配给 int 变量时我遇到了段错误
int main(int argc, char *argv[])
{
for (int i = 1; i < argc; i ++)
{
if (is_valid_int(argv[i]) == 1)
{
continue;
}
else
{
printf("%s is not a valid integer\n", argv[i]);
exit(0);
}
}
int size = atoi(argv[3]);
int lower = atoi(argv[4]);
int upper = atoi(argv[5]);
printf("%d%d%d", size, lower, upper);
generate_population(size, lower, upper);
return 0;
}
int *generate_population(int size, int lower, int upper)
{
int *my_array=(int*)malloc(size * sizeof(int));
for (int i = 0; i < size; i++)
{
my_array[i] = (rand() % (upper - lower + 1)) + lower;
}
for (int j = 0; j < size; j++)
{
printf("%d", my_array[0]);
}
return 0;
}
It does not print the values after I assign them.在我分配值后它不会打印这些值。 I tried commenting out call of generate_population()
and I still get the error.我尝试注释掉generate_population()
的调用,但仍然出现错误。
When you run ./stats 1 2 50 100
argv will be [0: "./stats", 1: "1", 2: "2", 3: "50", 4: "100"]
.当您运行./stats 1 2 50 100
argv 时,将是[0: "./stats", 1: "1", 2: "2", 3: "50", 4: "100"]
。 So there is no argv[5]
, it will be NULL on most os.所以没有argv[5]
,在大多数操作系统上它将是 NULL 。 The fix is:修复方法是:
int size = atoi(argv[2]);
int lower = atoi(argv[3]);
int upper = atoi(argv[4]);
Also you should check argc in case the user does not provide enough arguments.如果用户没有提供足够的 arguments,您还应该检查 argc。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.