Search code examples
cstrlenstrcat

strcat + strlen has strange behavior


guys i want to find the cause why this strcat (or strlen) has this issue:

when i write:

int main(int argc, char* argv[])
{
    if(argv[1] != '\0')
    {
        const char* navegador = "C:\\Program Files\\Mozilla Firefox\\firefox.exe ";
        const char* puerto  = "localhost:80/";
        char* archivo   = argv[1];

            char comando[2] = "\"";
            strcat(comando,navegador);
            int size = strlen(comando);         // ISSUE UNCOMMENTED!

        printf("command is: %s\n",comando);
    }
    else
    {
        printf("is null!\n");
    }
    return 0;
}

its output is:

D:\camil\Documents\mis_documentos\configs\sublime_text>program.exe someOption
command is: "C:\.

and when i comment the issue statement, its output is:

D:\camil\Documents\mis_documentos\configs\sublime_text>program.exe someOption
command is: "C:\Program Files\Mozilla Firefox\firefox.exe"

Why strlen changes the output, it seems strlen affects strcat behavior.


Solution

  • Provided all the command-line-arguments part is good, you should increase the size of comando[] as it is not enough to contain the concatenation part.

    It's size should be at least equal to strlen(comando) + strlen(navegador) + 1.

    When I increase the size of comando to (say) 200 then the output is: command is: "C:\Program Files\Mozilla Firefox\firefox.exe