Mail Archives: djgpp/1998/08/28/22:15:42
On Sat, 15 Aug 1998 13:15:28 -0300, Endlisnis <s257m AT unb DOT ca> wrote:
>Cephaler wrote:
>
>> int main(void) {
>> char *string1=(char *)malloc(80);
>> char *string2;
>> strcpy(string1,"foobar");
>> string2 = string1;
>> strcpy(string2,"raboof");
>> printf("%s\n",string1);
>> return(0);
>> }
>>
>> Or is this bad bad code?
>
> I don't see anything wrong with is (except maybe you didn't free your
>memory).
>
>> 2) Having not initialized string2, a) do I have to free string2 and b) does
>> that have any effect on string1? (oops didn't free string1)
>
> You only 'malloc'ed once, so you only need to 'free' once. Since both
>strings now point to the same location, just 'free' one of them. It doesn't
>matter which.
>
>> 3) concerning strcpy...is there any special reason why I shouldn't just use
>> string1 = "foobar" ?
>
> Not to my knowledge (except you can't 'free' that space).
>
The string1 pointer will be set to the first byte of the string
literal "foobar". Where "foobar" actually is doesn't matter, the
compiler handles it for you. ( BTW: you cant free() the literal
"foobar" because it is never allocated with malloc(), it is actually
embedded in the executable somewhere. )
- Mark -
>--
> (\/) Endlisnis (\/)
> s257m AT unb DOT ca
> Endlisnis AT GeoCities DOT com
> Endlis AT nbnet DOT nb DOT ca
>
>
>
>
- Raw text -