Segmentation error around strcpy?

I know that you will tear my knuckles, but.

Why segmentation error occurs

char* cmd; strcpy(cmd, argv[0]); 

If it is not

 char *cmd; cmd = "plop"; 

I have not practiced since, and I cannot remember why.

ps: in fact, I know that something like this, before strcpy, would be better

 char *cmd = (char*) malloc(strlen(argv[0])); 

but I'm just wondering why this segmentation error.

Thanks!

+4
source share
4 answers

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]; // for instance 

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); // no need to cast, by the way, unless you're in C++ 

This allocates whatever_you_need char on the heap. Remember to free memory with free as soon as you are done with it.

+9
source

You will get a seg. because cmd in your first example doesn't point to anything (or, rather, points to something that is undefined - so trying to read characters from or write characters to a pointer is likely to result in an access violation).

In the second example, you set cmd to specify a legal string of characters.

+5
source

If you want to easily make a copy of argv [0],

 char* cmd = strdup(argv[0]); 

Of course, you better check that the result of strdup is null or not. :)

+2
source

I'm just wondering why this segmentation error.

Because if cmd is a global variable, its value is NULL , which is not writable, and if it is a local variable, then its value is undefined and you should not use it (but it can do anything if you do, which in many cases is worse than NULL).

+1
source

All Articles