delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/08/28/22:15:42

From: wpp AT brinet DOT com
Newsgroups: comp.os.msdos.djgpp
Subject: Re: yet more questions about pointers
Date: Sat, 29 Aug 1998 01:14:13 GMT
Organization: http://extra.newsguy.com
Lines: 48
Message-ID: <35e754f4.2457929@cnews.newsguy.com>
References: <01bdc7e8$c1ff0e20$4ac3b8cd AT scully> <35D5B41F DOT 4534F8E4 AT unb DOT ca>
NNTP-Posting-Host: p-789.newsdawg.com
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

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 -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019