Mail Archives: djgpp/1997/12/02/21:30:26
At 07:01 12/1/1997 GMT, Paul Derbyshire wrote:
>
>Michael Phelps (loverns AT welchlink DOT welch DOT jhu DOT edu) writes:
>
>>> static char *string;
>
>...
>
>>> string = "Hello Bobby";
>>
>> Looks like a problem here. Try allocating memory for it:
>> string = (char *)malloc(strlen("Hello Bobby")+1);
>> strcpy(string, "Hello, Bobby");
>
>What a waste of ram!
>String is declared a pointer to char, it will start off NULL.
>The assignment string="Hello Bobby"; does this: At compile time, "Hello
>Bobby\0" is embedded in the data segment of the object code, and into the
>executable at link time. The assignment becomes an instruction to get the
>address for that bit in the data segment (specifically wherever it loads
>into the address space at run time) and stuff it at the address for
>"string", meaning the pointer changes to point to the string in the data
>segment. Which is perfectly valid, allocated memory, and which has been
>nicely null-terminated for you at compile time. There's nothing wrong with
>that line of the original code and no reason to allocate yet more space at
>run time and put a duplicate of the string in there.
You are quite right. The only difference is that in the original case
(char *s="message") the string will be read-only. I've forgotten whether the
original poster wanted to write into it or not, but that could be
significant. Also, slight pedantic point: constant strings are placed in the
code or `text' segment, not data.
Nate Eldredge
eldredge AT ap DOT net
- Raw text -