Modifying string literals (was Re: Are strings local?)

Barry Margolin barmar at think.COM
Fri Aug 5 02:23:55 AEST 1988


In article <652 at m10ux.UUCP> rgr at m10ux.UUCP (Duke Robillard) writes:
>During my search about this locality of statics business, I discovered
>a pretty bizarre thing about strings.  I dunno if it's just my System
>V compiler or what, but you can write to strings (since they're just
>static arrays of characters?)

Yes, compilers will allow this, but it is not a good idea, and I
believe that ANSI C specifically says that it is a no-no.  A compiler
is permitted to allocate string literals in read-only memory.  I think
it may also merge duplicate string literals, so that

	char *p,*q
	p = "abc";
	q = "abc"; /* Might use the same string as above */
	p[2] = 'd';
	printf("%s",q); /* this might print "abd"! */

Note that this kind of code will probably not get a compiler warning,
because a compiler can't in general tell whether a char* variable will
be pointing to a string literal or not.  Consider:

funct(string,flag)
char *string;
int flag;
{
	char *p;

	if (flag)
		p = "abc";
	else p = string;

	p[2] = 'd';	/* Whether this is valid depends on flag */
}

Another unusual case is due to the static allocation of the string
constants.  Consider:

funct2()
{
	char *p;
	p = "abc";
	if (p[2] == 'c') {
		printf("OK\n");
		p[2] = 'd';
	};
	else printf("Not OK\n");
}

The first time this is called it will print "OK\n", but every time
after that it will print "Not OK\n", even though it does 'p = "abc"'
each time, because it is actually changing "abc" to "abd".

Barry Margolin
Thinking Machines Corp.

barmar at think.com
{uunet,harvard}!think!barmar



More information about the Comp.lang.c mailing list