@Cymric
Fluffy isn't wrong, he is saying when you understand pointers properly, you know *why* the code he presented is so screwed up.
-edit-
It appears the 'bad' code is to make a function that will create a new unique copy of the source string.
-/edit-
For those who can't see it
First of all, he creates a single character 'result', gets a pointer (the address of the bit of memory where 'result' is) to it by using '&result'.
Next, he attempts to copy a string of characters to that piece of memory using a standard C function 'strcpy()' for copying strings. Strings in C are basically arrays of characters (that end in a zero byte). When you copy them, you copy the entire array from one place to another.
The result is that the memory beyond the space occupied by 'result' is overwritten. Variables like the one he declares here are created on the programs' stack, where all the important temporary information at any given instant lives. The effects of overwriting this memory are hence generally catastrophic to say the least...
The second error is that he returns the address of 'result' from the function. The problem here is that the actual character 'result', created on the stack, only exists during the lifetime of this function. Once you leave the function (by returning from it), that character effectively ceases to exist and its memory space is used by something else.
By returning its address, we can then later go back and use this variable which as we have just seen, no longer really exists. Any attempts to use the variable involve, once again, illegally messing up the stack resulting in another bomb out.
-edit-
Anyway, to fix this bad code, we need to create a genuine, seperate copy of the string and return its address. This means we need to dynamically allocate (that is, create an area in the computers 'free' memory) sufficient space to store a copy of the string, copy the characters accross and then return the address of this new bit of memory we have floating around.
char* clone(char* string)
{
char* result;
result = (char*)malloc(strlen(string)+1); /* Don't be a muppet like me and forget the +1 :-) */
strcpy(result, string);
return result;
}
This can be improved upon by checking that the allocation using malloc worked (check the value of 'result' to make sure it is not NULL) before we use it, but I ommited this check for the sake of clarity.
ie instert after the line with malloc() and before strcpy() the following check
if (result == NULL)
return NULL;