[英]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.