c - 随机播种段故障

标签 c debugging error-handling segmentation-fault

我被要求将随机种子放入一个程序中,当用户输入 -r 时调用该程序。它看起来像

-r1234567

因此,作为全局变量,我设置 Random = 1234567。

我也将其添加到我的函数的顶部:

printf("Seed: %d\n", Random);
srand48(Random);

每次我使用 -r1234567 我的程序都会出现段错误并显示以下内容:

Program received signal SIGSEGV, Segmentation fault.
____strtol_l_internal (nptr=0x0, endptr=0x0, base=10, group=<optimized out>, 
loc=0x7ffff7ad8020) at ../stdlib/strtol_l.c:298
298 ../stdlib/strtol_l.c: No such file or directory.
(gdb) bt
#0  ____strtol_l_internal (nptr=0x0, endptr=0x0, base=10, group=<optimized out>, 
loc=0x7ffff7ad8020) at ../stdlib/strtol_l.c:298
#1  0x00007ffff77589e0 in atoi (nptr=<optimized out>) at atoi.c:28
#2  0x0000000000401d8c in getCommandLine (argc=6, argv=0x7fffffffe238)
at prog.c:171
#3  0x0000000000401514 in main (argc=6, argv=0x7fffffffe238) at prog.c:35
(gdb) up
#1  0x00007ffff77589e0 in atoi (nptr=<optimized out>) at atoi.c:28
28  atoi.c: No such file or directory.
(gdb) up
#2  0x0000000000401d8c in getCommandLine (argc=6, argv=0x7fffffffe238)
at prog.c:171
warning: Source file is more recent than executable.

在我的命令中:情况如下:

 while ((c = getopt(argc, argv, "g:n:a:h:s:d:v:r")) != -1)

case 'r': Random = atoi(optarg);       break;

因此用户想要使用种子进行随机化。他们执行./program -r1234567。然后,这将进入我上面放置的两行代码,并且应该随机化。

有什么建议吗?

最佳答案

您的问题是 getopt 调用,因为您忘记告诉 getopt -r 参数采用一个值:

getopt(argc, argv, "g:n:a:h:s:d:v:r:")
/*                                 ^ */
/*                                 | */
/*                    Add colon here */

因此,当您调用 atoi 时,optarg 指针为 NULL

关于c - 随机播种段故障,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20137634/

相关文章:

c - 尝试计算 C 中大写字母的数量时获得随机增量

c - 错误检查及其增加的长度 - 是否有类似嵌入式系统编程的中断?

ios - 越狱设备上的调试服务器

javascript - 如何根据用户使用jquery输入的内容打开和关闭错误消息

mysql - 在 Mysql 中使用 C 变量

c - 为什么我的简单 C 程序向标准输出显示垃圾信息?

debugging - 重新运行 Postman 测试而不重新提交 API 请求

perl - 在 Perl 调试器和 CPAN 客户端中向上和向下箭头不再起作用

C作业,暂时忽略(我想我稍后会用一些代码重新发布)

PHP - CodeIgniter - 为 foreach() 提供的参数无效