"Sam C. Nicholson !!" wrote:
> Glenn Fowler wrote:
> > I've been at this so long you think I should know better
> >
> > I've been under the apparently mistaken assumption that
> > if I dilligently pepper struct definitions and subsequent
> > declarations and initializations with "const" that the compiler
> > will attempt to place that data in readonly text
> >
> > I've done this with the libast tables in conftab.c lc.c
> > but nm and size show the data going to the .data section
> >
> 
> Use elfdump, as nm doesn't tell the whole story, what with its a.out
> history.

The outout of "elfdump" looks Ok, too:
-- snip --
$ elfdump rodatatest | egrep "slime"
 [14] 0x000219a8 0x00000bd0 OBJT GLOB D 0 .data    blueslime
 [34] 0x00010c58 0x00000bd0 OBJT GLOB D 0 .rodata  greenslime
 [55] 0x000219a8 0x00000bd0 OBJT GLOB D 0 .data    blueslime
 [75] 0x00010c58 0x00000bd0 OBJT GLOB D 0 .rodata  greenslime
     [14]        blueslime
     [34]        greenslime
-- snip --

> In addition to .text and .data, there is .rodata. There are others, as well.
> 
> Using the following snippet, and fiddling with the const keyword:
> #include <stdio.h>
> 
> char *d = "diggy";
> const int c = 5;
> static int e();
> int main()
> {
> printf("%d\n", c);
> e(d);
> // d[0] = 'b';
> }
> 
> static int e(char *p) {
> 
> p[0] = 'a';
> }
> 
> And compiling alternately with Sun Studio 11 cc and /usr/sfw/bin/gcc, viz:
> cc -o main.cc main.c; gcc -o main.gcc main.c; elfdump main*cc | egrep
> '\|[cde] '
> 
> You can see just where the variables go.
> 
> Interestingly, with the code as above, gcc produces code that segfaults,
> and cc produces code that runs.

This is the expected behaviour if you write in a string literal since
compilers are allowed to put these data in reda-only section (gcc does
this by default since many years and starting with gcc4.0 the
"-fwriteable-strings" option is gone (which means the
standard-conformant behaviour is now a _must_)). AFAIK the ISO C
standard defines the result of writes to a string literal as "undefined"
(note that a string literal is _different_ from a string buffer, e.g.
array of char) ...

----

Bye,
Roland

-- 
  __ .  . __
 (o.\ \/ /.o) roland.mainz at nrubsig.org
  \__\/\/__/  MPEG specialist, C&&JAVA&&Sun&&Unix programmer
  /O /==\ O\  TEL +49 641 7950090
 (;O/ \/ \O;)

Reply via email to