Search code examples
clinuxargvargc

Why does this final.exe file execute in an infinite loop instead of the specified number as below?


  • final.exe file.
  • this executes infinitely or up to 50.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[]) 
{
   int i; 
    if (argc < 2)
    {
        printf("ERROR: You need at least one argument.\n");
        return 1;
    } 
   else 
   {
        int i, j;
          
           for(i=1;i<=(int)*argv[1];i++)
            {
                printf("\n");
                (void)system("test1.exe");
            }
    } 
}

test.c file contains :

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() 
{
  printf("Hello World");
}
  • Expected - For ex. : ./final 2 : The output should be Hello World Hello World , i.e, prints only 2 times and not infinitely.

Solution

  • (int)*argv[1] is using the character code of the first character as the number of iteration. Character codes are usually differ from the number that the character represents.

    To convert a string to corresponding number, you can use atoi() (if you don't care about invalid input).

            int i, j;
            int num = atoi(argv[1]);
              
               for(i=1;i<=num;i++)
                {
                    printf("\n");
                    (void)system("test1.exe");
                }