www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2001/07/26/11:06:21

Date: Thu, 26 Jul 2001 16:32:41 +0300 (IDT)
From: Eli Zaretskii <eliz AT is DOT elta DOT co DOT il>
X-Sender: eliz AT is
To: Sergey Kovalev <kos AT kbtem DOT by>
cc: djgpp AT delorie DOT com
Subject: Re: Why so?
In-Reply-To: <9jp3tu$vb6c$1@ID-89475.news.dfncis.de>
Message-ID: <Pine.SUN.3.91.1010726162726.1520A-100000@is>
MIME-Version: 1.0
Reply-To: djgpp AT delorie DOT com
Errors-To: nobody AT delorie DOT com
X-Mailing-List: djgpp AT delorie DOT com
X-Unsubscribes-To: listserv AT delorie DOT com

On Thu, 26 Jul 2001, Sergey Kovalev wrote:

> Why this code produces following results?
> 01234
> 01234
> 01234567
> 67

Because it has a bug:

>   str=(char*)malloc(10);
>   clrscr();
>   str="01234";

The last line should be:

    strcpy(str, "01234");

Doing `str="01234";' is something _very_ different: you in effect throw 
away the buffer allocated with malloc, and instead make `str' to point to 
a _constant_ string "01234".  That string doesn't have enough space to 
hold more than 6 characters, so when you append "567" you get what is 
diplomatically called ``undefined behavior'', meaning that anything can 
happen.  In environments other than DJGPP, where constant strings are put 
in write-protected storage, your program will simply crash.

> Other compilers give me:
> 01234
> 01234
> 01234567
> 01234567

Most probably, 16-bit compilers such as Borland, which are notorious for 
letting such bugs remain in the code.

- Raw text -


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