Skip to contentSkip to conversation

Are string literals _always_ allocated in the RO section?

DISCUSSION Denis Zaitsev 4 participants 5 messages Jan 15, 2005 – Jan 17, 2005

lore
Share & tools
lore
#0 lore raw

This program:

void x(char *s)

{
    *s= 'x';
}

main()

{
    x("y");
}

is compiled plainly but cathes SIGSEGV in the

        *s= 'x' 

line. And it's because the string "y" is put in the .text section. And the fact that the x()'s parm is explicitly declared as <char*>, not <const char*> does nothing in this case. Should it be considered as a bug?

#1 lore raw
Quoted 12 lines · Denis Zaitsev

This program:

void x(char *s)

{
    *s= 'x';
}

main()

{
    x("y");
}
Quoted 5 lines

is compiled plainly but cathes SIGSEGV in the

        *s= 'x'

line.

That's what's supposed to happen. Storing into a string constant is invalid C.

#3 lore raw
In reply to Denis Zaitsev

Denis Zaitsev <[email protected]> writes:

| This program:
| 
| void x(char *s)
| {
|     *s= 'x';
| }
| 
| main()
| {
|     x("y");
| }
| 
| is compiled plainly but cathes SIGSEGV in the 
| 
|         *s= 'x' 
| 
| line.  And it's because the string "y" is put in the .text section.
| And the fact that the x()'s parm is explicitly declared as <char*>,
| not <const char*> does nothing in this case.  Should it be considered
| as a bug?

In the program? Yes.

-- Gaby

#4 lore raw

On Sun, 2005-01-16 00:18:20 +0100, Gabriel Dos Reis <[email protected]> wrote in message <[email protected]>:

Quoted 14 lines

Denis Zaitsev <[email protected]> writes:

| This program:
| 
| void x(char *s)
| {
|     *s= 'x';
| }
| 
| main()
| {
|     x("y");
| }
Quoted 4 lines

| not <const char*> does nothing in this case. Should it be considered | as a bug?

In the program? Yes.

Maybe you'd tell him more about the magic :)

char *mytext = "hello";

results in a pointer (which you may later on make pointing to a different location) that points to a static, read-only string containing "hello\0". However, if you need to change the text, you need to do it like this:

char mytext[] = "hello";

Cf. section 6.4.5.6 of the C99 standard.

MfG, JBG

Signature · 4 lines
Jan-Benedict Glaw       [email protected]    . +49-172-7608481             _ O _
"Eine Freie Meinung in  einem Freien Kopf    | Gegen Zensur | Gegen Krieg  _ _ O
 fuer einen Freien Staat voll Freier Bürger" | im Internet! |   im Irak!   O O O
ret = do_actions((curr | FREE_SPEECH) & ~(NEW_COPYRIGHT_LAW | DRM | TCPA));