0

I'm trying to get the user argv and print in the screen the result. Here is my following code:

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

int main (int argc, char *argv[])
{
    if (argc >= 1)
    {
        char *command = "gcc ";
        strcat(command, argv[1]);
        printf("%s", command);
        return 0;
    }
}

It compiles, but every time I execute it says that "Windows stoped to work". Basically, if the user does:

myprogram.exe test

the output might be

gcc test

Where is my error?

nobody
  • 19,814
  • 17
  • 56
  • 77

3 Answers3

3

You need your destination argument to strcat to be large enough to hold everything, ie

char command[50];
strcpy(command, "gcc ");
strcat(command, argv[1]);
Henry
  • 6,502
  • 2
  • 24
  • 30
  • It worked with 5001 instead of 50. Thank you –  May 24 '14 at 04:32
  • Keep in mind the other answers with dynamic allocation - you may eventually get some input that will *not* fit into an array of 5001 :) – Henry May 24 '14 at 04:33
  • 3
    This causes undefined behaviour; `strcat` appends to an existing string but `command` is uninitialized. You should either start with `strcpy`, or initialize `command[0]` at least to `0`. – M.M May 24 '14 at 04:54
1

You need to allocate memory to the char pointer before using strcat. Because char *command = "gcc" will be just pointing to a memory location. Before writing in that location you will have to allocate memory using malloc or change it to an array.

crack_jack
  • 54
  • 5
1
char *command

just declares an array without pointing to any space. You need to allocate space to the pointer before using it or you can use character array.

char command[100]="string";

or

 char *command = (char*) malloc (size);

And then you can use strcat like you have used.

coder hacker
  • 4,819
  • 1
  • 25
  • 50
  • 1
    `char *command;` declares a pointer, not an array. Also, OP's code actually does point it to some space. And don't cast malloc. – M.M May 24 '14 at 04:55
  • Why shouldn't malloc be cast? – coder hacker May 24 '14 at 05:03
  • [see here](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). The cast has zero good effects and non-zero bad effects. – M.M May 24 '14 at 05:05