[英]C program causing segmentation fault
下面我有一个 C 程序写在 UNIX 上。 我遇到分段错误。 我没有得到我遗漏的东西。 任何人都可以请帮忙。
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
char* app_name = NULL;
char* pInFile = NULL;
int main(int argc, char *argv[])
{
char* arg0 = argv[0];
char* pdebug = "miecf";
char* pLogfile = NULL;
char* pUserid = NULL;
char* pOutFile = NULL;
int c;
while( (c = getopt(argc, argv, ":a:d:i:l:u:o")) != EOF)
{
switch (c)
{
case 'a':
app_name = optarg;
break;
case 'd':
pdebug = optarg;
break;
case 'i':
pInFile = optarg;
break;
case 'l':
pLogfile = optarg;
break;
case 'u':
pUserid = optarg;
break;
case 'o':
pOutFile = optarg;
break;
default:
fprintf( stderr, "unknown option \'%c\'\n", optopt );
break;
} /* switch(c) */
} /* while( getopt()) */
printf("app_name is [%s]\n",app_name);
printf("pdebug is [%s]\n",pdebug);
printf("pInFile is [%s]\n",pInFile);
printf("pLogfile is [%s]\n",pLogfile);
printf("pUserid is [%s]\n",pUserid);
printf("pOutFile is [%s]\n",pOutFile);
return 0;
}
运行命令
-a test -d deimf -i input.txt -l log.txt -u bc@abc -o out.txt
Output
app_name is [test]
pdebug is [deimf]
pInFile is [input.txt]
pLogfile is [log.txt]
pUserid is [bc@abc]
run[2]: 10448 Segmentation Fault(coredump)
数据库报告
program terminated by signal SEGV (no mapping at the fault address)
0xff232370: strlen+0x0050: ld [%o2], %o1
(dbx) where
=>[1] strlen(0x0, 0xfffffaf0, 0x0, 0xffbff1a8, 0x0, 0x2b), at 0xff232370
[2] _ndoprnt(0x10f77, 0xffbff26c, 0xffbfe8e9, 0x0, 0x0, 0x0), at 0xff29e4d4
[3] printf(0x10f68, 0x21100, 0x0, 0x2111e, 0xff3303d8, 0x14), at 0xff2a0680
[4] main(0xc, 0xffbff304, 0xffbff4ad, 0xffbff4b8, 0x0, 0xffffffff), at 0x10e8
问题是当您尝试打印 pOutFile 时,它是 NULL。 许多操作系统(libc)不处理这个问题,你试图让它打印一个没有值的变量。
尝试这个:
if (pOutFile != NULL)
printf("pOutFile is [%s]\n",pOutFile);
else
printf("pOutFile is NULL\n");
添加:
即使您指定了 -o 开关,pOutFile 也没有值,因为您没有在 getopt 调用中的 o 之后放置 a:。 具体来说:s 出现在字母之后。 应该是这样的:
while( (c = getopt(argc, argv, "a:d:i:l:u:o:")) != EOF)
看起来你在这条线上有段错误:
printf("pOutFile is [%s]\n",pOutFile);
从你的命令行来看,你没有使用-o
开关,所以pOutFile
仍然是 NULL,但你正在尝试printf
它。
缺少:
是问题所在:
while( (c = getopt(argc, argv, ":a:d:i:l:u:o:")) != EOF)
^
“运行命令 -a test -d deimf -i input.txt -l log.txt -u bc@abc out.txt”
您只是忘记提供 -o 选项:
运行命令 -a test -d deimf -i input.txt -l log.txt -u bc@abc -o out.txt
您没有在“out.txt”之前传递 -o,因此您在 pOutFile 的 printf 中取消引用 null 指针。 这就是我第一眼注意到的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.