Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!cornell!uw-beaver!mit-eddie!bloom-beacon!apple!austing From: austing@Apple.COM (Glenn L. Austin) Newsgroups: comp.lang.c Subject: Re: char *Foo VS. char Bar[] Message-ID: <28957@apple.Apple.COM> Date: 14 Apr 89 16:32:31 GMT References: <19636@iuvax.cs.indiana.edu> Organization: Apple Computer Inc, Cupertino, CA Lines: 40 > char *foo = " "; > ... > sprintf(foo,"xxxx"); > >Using gcc on a VAX8650/Ultrix, the sprintf causes a bus error. The standard >cc compiler produced code that "worked". I had him change the declaration to > > char foo[6] = " "; /* assume I got the lengths correct */ > >and the program ran correctly as compiled by gcc. > >My interpretation is that, in the original case, gcc has created a >(variable) pointer which is initialized to some *constant* storage which >can't be written to; cc doesn't make any writeable/read-only distinctions. >The second form created a (constant?) pointer to some storage that is >explicitly writeable, and happens to be filled with blanks initially. > >(BTW: He says that the original form worked under MSC under MSDOS, so I >infer that MSDOS/80x86 systems also don't enforce constant strings.) I have found that this is a common problem. You are correct in your assumption that in the first case a pointer was created that pointed to a constant declaration, and in the second case, space was allocated on the stack for an array of characters that gets "preset" to spaces. The fact that MSC under MSDOS misses this shows how limited the OS is. Under protected mode, depending on the compiler (I haven't used MSC under OS/2 yet), you should also get a bus error. Incidentally, a Mac program written in MPW C 3.0 will also halt with a bus error on this code. ----------------------------------------------------------------------------- | Glenn L. Austin | The nice thing about standards is that | | Apple Computer, Inc. | there are so many of them to choose from. | | Internet: austing@apple.com | -Andrew S. Tanenbaum | ----------------------------------------------------------------------------- | All opinions stated above are mine -- who else would want them? | -----------------------------------------------------------------------------