我被要求将随机种子放入一个程序中,当用户输入 -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/