I know that you will rap me over the knuckles but.
Why does it make Segmentation fault
char* cmd;
strcpy(cmd, argv[0]);
when this doesn’t
char *cmd;
cmd = "plop";
I didn’t practice since a while, and can’t remember why.
ps: actually, i know that something like that, before the strcpy, would be better
char *cmd = (char*) malloc(strlen(argv[0]));
but i’m just wondering why this segmentation fault.
Thanks !
When you do:
You’re allocating a pointer on the stack. This pointer is not initialized to any meaningful value.
Then, when you do this:
You copy the string contained in
argv[0]to the address pointed tocmd, which is… something meaningless. Since you’re lucky, it simply segfaults.When you do this:
You assign to
cmdthe address to a statically allocated string constant. Since such strings are read only, writing on them is undefined behavior.So, how to solve this? Allocate memory for the runtime to write to. There’s two ways:
The first one is to allocate data on the stack, like this:
This allocates an array of 100
chars on the stack. However, it’s not necessarily robust, because you must know in advance how much memory you’ll need. The stack is also smaller than the heap. Which leads us to option number 2:This allocates
whatever_you_needchars on the heap. Don’t forget to release the memory withfreeonce you’re done with it.