Thread: Bug in C code

    #1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2003
    Posts
    245
    Rep Power
    12

    Bug in C code


    Print statement never executed

    ./getdata long

    =========================================
    Code:
    #include <stdio.h>  
    #include <stdlib.h> 
    
    char *progam_name;
    char *parameter1;
    
    main(argc, argv)
      int argc;
      char *argv[];
     {
        progam_name = argv[0];
        parameter1  = argv[1];
    
        if (argc < 2)
          do_process_1();
        else
          if (argc == 2 && parameter1 == "long")
    PROBLEM -->>          printf ("parameter1 = %s\n", parameter1);
     }
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Posts
    55
    Rep Power
    12
    parameter1 is a pointer to a location in memory, this location is the beginning of the values 'l', 'o', 'n', 'g', '\0' you cannot compare all of these values in one go using ==.

    You need to compare each value individually, for example:
    char *p1 = argv[1]; /* this should be check first... */

    Code:
    if(strlen(argv[1]) > 3)
    {
    	if(*p1 == 'l' && *(p1+1) == 'o' && *(p1+2) == 'n' && *(p1+3) == 'g' && *(p1+4) == '\0')
    	{
    		printf("parameter1 == %s\n", p1);
    	}
    }
    Look into the function "strcmp", from string.h.
    You would use it follows:

    Code:
    int res;
    	
    res = strcmp(argv[1], "long");
    if(res == 0)
    {
    	printf("argv[1] == %s\n", argv[1]);
    }
    Please remember error checking should be used to check that these arguments actually exist before attempting to access the memory of them.
    Last edited by xtor; August 13th, 2003 at 07:09 PM.
    Mo0 Developments - Programming community.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2003
    Posts
    245
    Rep Power
    12

    reply


    Thank you for your help. This is one of my most common mistake. You must use the strncmp, not direct comparison.
    Too many languages, too many syntax, and different features.

IMN logo majestic logo threadwatch logo seochat tools logo