Jack posted:
The following code causes "Segementation fault":
char *s1;
char *s2;
When you define a variable within a function without initialising it, it
contains white noise -- a bit-pattern left over from the last time that
memory was used. (Except if the object is static... but I won't get into
that just now).
An int variable holds an integer numerical value.
A pointer variable holds a memory address.
You define "s1" without initialising it -- as far as you're concerned, it
contains a random value. For the purpose of this demonstration, let's
assume that this "random memory address" is 2349538.
You also define "s2" without initialising it, but that's okay because you
set its value soon after.
"s2" now contains the memory address of the first char in that string
literal. (I would advocate using pointer-to-const for this purpose).
You copy the string located at the memory address specified by s2 to the
memory address specified by s1. So basically you're copying "Hello" to
our random memory address of 2349538.
The memory address 2349538 isn't yours to access -- it could contain
important data.
If I modify the code to:
char *s1;
char *s2;
s2 = "HELLO";
s1 = (char*)malloc(10 * sizeof(char));
Here you allocate 10 bytes of memory.
You then set the value of "s1" to the address of the first byte.
"s1" no longer contains a random value -- it contains a legitimate value;
you allocated those 10 bytes, and now you're free to use them in whatever
way you please.
Here you copy "Hello" to the address specified by "s1". The address
specified by "s1" is the 10 bytes of memory you allocated. This is fine.
The code works well. So I should always allocate memory for s1, before
I call strcpy, right?
I find it handy to repeat to yourself, "A pointer stores a memory
address".
If you're going to be accessing the data stored at a memory address, you
must make sure you are allowed access the memory in question.
-Tomás