Path: utzoo!utgpu!attcan!uunet!lll-winken!lll-tis!helios.ee.lbl.gov!pasteur!ucbvax!CITI.UMICH.EDU!rees
From: rees@CITI.UMICH.EDU
Newsgroups: comp.sys.apollo
Subject: Re: String copy problem
Message-ID: <8808181725.AA28065@umix.cc.umich.edu>
Date: 18 Aug 88 17:07:23 GMT
References: 
Sender: daemon@ucbvax.BERKELEY.EDU
Reply-To: rees@caen.engin.umich.edu (Jim Rees)
Organization: The Internet
Lines: 21


          You could also use malloc to allocate space for the string, i.e.,
     
               str1 = (char *)malloc( sizeof( *argv[1] ));

Well that's clearly wrong, but I want to point out that a lot of programs
try to do this:

               str1 = (char *) malloc(strlen(argv[1]));

which is also wrong.  It happens to work on some systems because of a
coincidence in the way malloc works.  The correct code leaves room for
the null terminator:

               str1 = (char *) malloc(strlen(argv[1]) + 1);

If you don't do this, the null terminator wipes out whatever is after the
allocated space.  In some implementations, this is OK, because the next
thing will be another malloc block with an address in the first word.
As long as the address is less than 2^24, the first byte will be null
(on big-endian machines) and you're OK.  On an Apollo it's not OK.
-------