tags:

views:

428

answers:

3

Hi,

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

+1  A: 

My understanding from (http://linux.die.net/man/3/optarg) is that optarg points to the contents of the argv buffer so the strdup isn't necessary. The suggestion to use const char* seems a reasonable idea.

tonylo
+1  A: 

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.

Jonathan Leffler
+1  A: 

Both are good pieces of advice. You probably don't want to change dir and bld, so declaring them as const char * instead of char * is useful in any case because the compiler will detect more coding errors. By getting rid of the strdup you are just avoiding an unnecessary copy (depending on what you do with dir afterwards), but it creates an alias to your optarg.

David Nehme