Search code examples
cconstantsstrdup

Whether const char * and strdup serve the same function when used with getopt in C?


In the below code snippet can i replace char * to const char * and remove the strdup() function call and directly take the optarg value set by getopt()? I am advised to use const char * to skip the strdup function usage. Appreciate the help in advance.

/* Code Snippet */
char *dir = NULL; 
char *bld = NULL;
int chr;

while ( ( chr = getopt( argc, argv, "d:a:b:f:" ) ) != -1 ) {

 switch ( chr ) {

  case 'd': //Directory parameter
   dir = strdup( optarg );
   if (dir == NULL) { /*Error*/ }

  case 'b': //Build parameter
   bld = strdup( optarg );
   if (bld == NULL) { /*Error*/ }
  ...other code...
 }
} 

I really don't understand the need for doing so.

Edit: Thanks for the answers. It was really helpful. I modified the code to const char * and skipped the strdup call.

Thanks, Liju


Solution

  • Since optarg is declared as 'extern char *optarg;', you do not have to use 'const char *', but it is good practice not to modify the arguments to your program. It will depend more, I suggest, on whether the functions you call with your dir and bld variables are const-correct. If they are your code, you can make them so; if not, you may find it simpler to keep the variables non-const. Your call to 'strdup()' (which is standard in POSIX, but not in C - as in ISO/IEC 9899:1999) is unnecessary.