Re: where is the string literal allocated ? On the stack ?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 




----- Original Message ----- From: "Brian Dessent" <brian@xxxxxxxxxxx>
To: "Michael Gong" <mwgong@xxxxxxxxxxxxxx>
Cc: <gcc-help@xxxxxxxxxxx>
Sent: Friday, April 20, 2007 12:28 PM
Subject: Re: where is the string literal allocated ? On the stack ?


Michael Gong wrote:

Though it's not related with gcc, could anyone help me with following
question:

Where is the string literal allocated ? Is it on the stack ?

For example, where is "abc" allocated ?

char * foo() {
    return "abc";
}

Everyone else has already answered your question directly, but I'd like to point out that the compiler is not a black box -- you can easily see exactly what it's doing with a few simple commands. Check the docs for
on -S, -save-temps, -fverbose-asm, etc.  For example:

$ echo 'char * foo() { return "abc"; }' | gcc -x c - -S -o
-
       .file   ""
       .section        .rodata
.LC0:
       .string "abc"
       .text
.globl foo
       .type   foo, @function
foo:
       pushl   %ebp
       movl    %esp, %ebp
       movl    $.LC0, %eax
       popl    %ebp
       ret
       .size   foo, .-foo
       .ident  "GCC: (GNU) 4.0.4 20060507 (prerelease) (Debian
4.0.3-3)"
       .section        .note.GNU-stack,"",@progbits

As you can see, it goes in the .rodata section.  The above is the
behavior under linux, but for PE (Win32) it is a different section:

$ echo 'char * foo() { return "abc"; }' | gcc -x c - -S -o -
       .file   ""
       .section .rdata,"dr"
LC0:
       .ascii "abc\0"
       .text
.globl _foo
       .def    _foo;   .scl    2;      .type   32;     .endef
_foo:
       pushl   %ebp
       movl    %esp, %ebp
       movl    $LC0, %eax
       popl    %ebp
       ret

That is my second point: this kind of thing is platform-dependant
(although it can never be on the stack), and you didn't mention at all
what platform you are using in your original question, which should be a
requirement for almost any compiler/toolchain question.

Brian


Thanks for the comments.

Actually, I don't care about the exact location :-) All I need to know is whether it is on the stack. Therefore, I don't mention the platform in the question.

Mike







[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux