C-программа, вызывающая ошибку сегментации - PullRequest
2 голосов
/ 03 июня 2011

У меня есть программа на 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

Вывод

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)

Dbx Report

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

Ответы [ 5 ]

9 голосов
/ 03 июня 2011

Проблема в том, что pOutFile равен NULL, когда вы пытаетесь распечатать его.Многие ОС (libc) не справляются с этим, и вы пытаетесь заставить его напечатать переменную, которая не имеет значения.

Попробуйте это:

if (pOutFile != NULL)
    printf("pOutFile is [%s]\n",pOutFile);
else
    printf("pOutFile is NULL\n");

Добавлено:

pOutFile не имеет значения, даже если вы указали ключ -o, потому что вы не поставили: после o в вызове getopt.В частности: s приходят после письма.Должно быть так:

while( (c = getopt(argc, argv, "a:d:i:l:u:o:")) != EOF)
3 голосов
/ 03 июня 2011

Отсутствует : проблема:

while( (c = getopt(argc, argv, ":a:d:i:l:u:o:")) != EOF)
                                            ^
3 голосов
/ 03 июня 2011

Похоже, что вы segfaulting в этой строке:

    printf("pOutFile is [%s]\n",pOutFile);

Судя по вашей командной строке, вы не используете переключатель -o, поэтому pOutFile остается NULL, но выпытаясь printf это.

2 голосов
/ 03 июня 2011

Вы не передали -o до "out.txt", поэтому вы разыменовываете нулевой указатель в printf pOutFile.Вот что я заметил на первый взгляд.

2 голосов
/ 03 июня 2011

"Выполнение команды -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

...