C程序导致分段错误

Sac*_*iya 2 c unix segmentation-fault

我在UNIX上编写了一个C程序.我得到分段错误.我没有得到我错过的东西.谁能请帮忙.

#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;
}
Run Code Online (Sandbox Code Playgroud)

运行命令

-a test -d deimf -i input.txt -l log.txt -u bc@abc -o out.txt
Run Code Online (Sandbox Code Playgroud)

产量

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)
Run Code Online (Sandbox Code Playgroud)

Dbx报告

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
Run Code Online (Sandbox Code Playgroud)

Wes*_*ker 9

问题是当您尝试打印时pOutFile为NULL.许多操作系统(libc)都没有处理这个问题,你试图让它打印一个没有值的变量.

试试这个:

if (pOutFile != NULL)
    printf("pOutFile is [%s]\n",pOutFile);
else
    printf("pOutFile is NULL\n");
Run Code Online (Sandbox Code Playgroud)

添加:

即使你指定-o开关,pOutFile也没有值,因为你没有在getopt调用中的o之后放一个:.特别是:在信之后来了.它应该是这样的:

while( (c = getopt(argc, argv, "a:d:i:l:u:o:")) != EOF)
Run Code Online (Sandbox Code Playgroud)

  • 更新.调用printf并且*假设*您的用户提供了一个值仍然是不安全的,所以即使您修复了-o问题,我仍然建议使用上面的值检查. (2认同)