Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!purdue!decwrl!labrea!csli!gandalf From: gandalf@csli.STANFORD.EDU (Juergen Wagner) Newsgroups: comp.lang.c Subject: Re: modification of strings Keywords: string, constants, pointers Message-ID: <7429@csli.STANFORD.EDU> Date: 5 Feb 89 00:54:07 GMT References: <345@lakesys.UUCP> Reply-To: gandalf@csli.stanford.edu (Juergen Wagner) Organization: Xerox Palo Alto Research Center, Palo Alto, CA Lines: 55 In article <345@lakesys.UUCP> chad@lakesys.UUCP (D. Chadwick Gibbons) writes: >... > Insofar as I have been told, strings can not >be modified - note, the type char *blah = "this is a string"; not the everyday >normal strings we use. This would appear that if you attempted to modify >their contents, you would either get a core dump of some various flavor, or >the program would ignore your request. Actually, the effect you get depends on the system you're trying this on. If your machine puts the string into text space, together with your code (HP-UX does that), you loose when you try to change the string. Other systems usually have a loader option to specify this behavior. For the sake of portability, assume constant strings are read-only. >...[TFM quote deleted] > > char *blah = "meow"; > char *tmp; > > tmp = strcpy(blah, "grr, snarl, hiss"); Ok. New let's see what this piece of code does. 'blah' is a pointer to char. It is initialized to point at the first character of the char vector < 'm', 'e', 'o', 'w', '\0' > which occupies five bytes. 'tmp' is just another pointer to char but uninitialized. The strcpy statement copies a string of length (humph!) 16 + 1 (for the zero byte) into consecutive byte locations from the point 'blah' points to on. Hmmm.... your compiler allocated five bytes for the string but you are now using 17 for the new string. Strcpy will just overwrite whatever follows the string. If that happens to be another statically allocated string, it will show changed contents. If that happens to be some data space, variables seem to change values. If that happens to be just beyond the allocated memory page, you get some kind of error (segmentation fault et al.). If your compiler happily put the string in the midst of code, you will either overwrite code or get some error like segmentation fault (text space is Read-Only). If the string was allocated on the stack, your return address might be f***ed up. If.... As you can see, there is a vast number of alternatives, and you tried some of them. As a rule of thumb, I suggest to check calls to destructive functions like strcat, strcpy, et al. very carefully. Sometimes, they cause errors by over- writing pieces of memory used in completely different portions of your program, and the stuff becomes hard to debug. Allocate all the memory you need, and don't try to overwrite static strings. -- Juergen Wagner gandalf@csli.stanford.edu wagner@arisia.xerox.com