delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2001/07/26/11:54:29

Sender: tim AT picard DOT skynet DOT be
Message-ID: <3B602371.86D2F40E@falconsoft.be>
Date: Thu, 26 Jul 2001 16:04:33 +0200
From: Tim Van Holder <tim DOT vanholder AT falconsoft DOT be>
Organization: Anubex N.V.
X-Mailer: Mozilla 4.77 [en] (X11; U; Linux 2.2.16-3 i686)
X-Accept-Language: en, nl-BE, nl
MIME-Version: 1.0
To: Martin Str|mberg <ams AT father DOT ludd DOT luth DOT se>, djgpp AT delorie DOT com,
kos AT kbtem DOT by
Subject: Re: Why so?
References: <9jp3tu$vb6c$1 AT ID-89475 DOT news DOT dfncis DOT de> <996152804 DOT 153539 AT queeg DOT ludd DOT luth DOT se>
Reply-To: djgpp AT delorie DOT com

> :   str="01234";
> :   puts(str);
> :   printf("%s\n",str);
> :   strcat(str,"567");
> :   puts(str);
> :   printf("%s\n",str);
> :   return 1;
> 
> : Why this code produces following results?
> : 01234
> : 01234
> : 01234567
> : 67
> 
> : Other compilers give me:
> : 01234
> : 01234
> : 01234567
> : 01234567
> 
> Only (bad) luck.

Actually, no - it IS odd.  With the code he posted, if the strcat does
not cause a segmentation fault, you'd expect the output he posted as
resulting from other compilers; the relevant snippet is:

> :   puts(str);
> :   printf("%s\n",str);

Regardless of what str points to, neither of these modify str in any
way, so both should print the same value.  At the very least,
"012345" should appear; the rest is memory that might have been
changed, as it does not belong to the string constant.

In any case, the solution to the problem is simply to change

  str = "01234"

to

  strcpy (str, "01234");

(and adding a 'free(str)' at the end).

-- 
Tim Van Holder - Anubex N.V.
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
This message was posted using plain text. I do not endorse any
products or services that may be hyperlinked to this message.

- Raw text -


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