string sharing (possible bug?)

Adam P. Jenkins ajenkins at javanet.com
Thu Dec 10 01:30:58 UTC 1998


It is illegal to modify string literals in C or C++.  That's why the C
compiler is free to share string literals.  Many compilers place string
literals in the read-only section of the program image, so your foo()
function would get a segmentation fault at runtime.  Most modern C compilers
would also warn you at compile time if you tried to modify a string literal
directly.  Obviously if you modify it through a char* the compiler may not
be able to tell that it points to a string literal.

I've used a lot of different programming languages, and Smalltalk is the
only language I've seen that shares string literals *and* allows them to be
modified.  That's why I thought it was a bug when I discovered this.

> FWIW, C compilers can share string literals too and the exact same problem
> can result.
>
> void foo()
> {
>    char* b = "abc";
>    printf("%s\n",b);
>    b[1] = 'd';
> }
>
> void main()
> {
>    foo(); // prints abc
>    foo(); // prints abd
> }
>
> Java also shares equivalent strings but lacks this problem because strings
> are always immutable (mods produce new strings).

Python, and I believe ML, also have immutable strings.

Adam





More information about the Squeak-dev mailing list