Mail Archives: djgpp/2001/07/26/11:06:21
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 -