简体   繁体   中英

Parsing argc and argv[] parameter in c

I have written the following program which is working fine when I compile the program in x86 configuration but when I change the configuration of the platform to x64, my program doesn't work at all. Where is the problem:

int main(int argc, char* argv[])
{
    char* cp_UserName[MAX_PATH];
    char* cp_DomainName[MAX_PATH];
    char* cp_HashNtlm[MAX_PATH];
    char* cp_ComputerName[MAX_PATH];

    DnPthIconSetup();
    DnPthInitialization(TRUE);

    if (argc > 4)
    {
        for (size_t i = 1; i <= sizeof(argv); i++)
        {
            if (strstr(argv[i], "user") != NULL)
            {
                strtok_s(argv[i], ":", cp_UserName);
            }
            if (strstr(argv[i], "domain") != NULL)
            {
                strtok_s(argv[i], ":", cp_DomainName);
            }
            if (strstr(argv[i], "pc") != NULL)
            {
                strtok_s(argv[i], ":", cp_ComputerName);
            }
            if (strstr(argv[i], "ntlm") != NULL)
            {
                strtok_s(argv[i], ":", cp_HashNtlm);
            }
        }

        printf("%s\n", *cp_UserName);
        printf("%s\n", *cp_DomainName);
        printf("%s\n", *cp_ComputerName);
        printf("%s\n", *cp_HashNtlm);
        system("PAUSE");
        // ParametricCredentialDispatcher(cp_UserName, cp_DomainName, cp_HashNtlm, cp_ComputerName);
    }
    else if (argc == 1)
    {
        InteractiveMode();
    }
    else
    {
        printf("\nUsage: ./program user:[] domain:[] pc:[] ntlm:[]\n");
        system("PAUSE");
    }


    return 0;
}
  • sizeof(argv) is a size of the pointer, not number of arguments.
  • Your usage of strstr will result into wrong result when, for example, the arguments contains pc:computer_for_an_user .
  • This usage of strtok_s will store pointer to the name of configurations, not their values.

Possible fix of the parsing part:

for (size_t i = 1; i < arc; i++)
{
    if (strncmp(argv[i], "user:", 5) != NULL)
    {
        *cp_UserName = strchr(argv[i], ':') + 1;
    }
    if (strncmp(argv[i], "domain:", 7) != NULL)
    {
        *cp_DomainName = strchr(argv[i], ':') + 1;
    }
    if (strncmp(argv[i], "pc:", 3) != NULL)
    {
        *cp_ComputerName = strchr(argv[i], ':') + 1;
    }
    if (strncmp(argv[i], "ntlm:", 5) != NULL)
    {
        *cp_HashNtlm = strchr(argv[i], ':') + 1;
    }
}

The added : in the arguments of strncmp is assuming that strchr won't return NULL .

Also you should initialize the pointers and check if they are not NULL before passing them to printf .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM