When you do:
char * cmd;
You allocate a pointer to the stack. This pointer is not initialized to any significant value.
Then when you do this:
strcpy(cmd, argv[0]);
You copy the line contained in argv[0] to the address given in cmd , which ... something is meaningless. Since you're in luck, these are just segfaults.
When you do this:
cmd = "plop";
You assign cmd address to a statically assigned string constant. Since such strings are read-only, writing to them is undefined behavior.
So how to solve this? Allocate memory for runtime for recording. There are two ways:
The first of these is the allocation of data on the stack, for example:
char cmd[100];
An array of 100 char on the stack is allocated here. However, this is not necessarily reliable, because you must know in advance how much memory you will need. The stack is also smaller than the heap. Which brings us to option number 2:
char *cmd = malloc(whatever_you_need);
This allocates whatever_you_need char on the heap. Remember to free memory with free as soon as you are done with it.
source share