Reputation: 235
I have a very basic question. Lets take this snippet:
#include <stdio.h>
void foo(void) {
char *s = "StackOverflow";
printf("%s\n", s);
}
int main(void) {
foo();
}
In the process execution stack, main gets loaded on to the stack, then foo() gets called. Now, where is the memory for "StackOverflow" allocated? Similarly where is the memroy for "%s\n" allocated when printf is called?
Consider the following code:
Now the other question I have is, considering the below code:
#include <stdio.h>
int x;
int abc = 100;
void foo(void) {
char *s = "stackoverflow";
printf("%s\n", s);
}
int main(void) {
foo();
}
So, if I do objdump -s -j .bss a.out , I should see uninitialized segment and if I do objdump -s -j .data a.out , I should see initialized segment (abc=100) rt? Is there anything wrong with this assumption?
I get the following outputs though:
test > objdump -s -j .bss a.out a.out: file format elf32-i386
test > objdump -s -j .data a.out
a.out: file format elf32-i386
Contents of section .data: 804954c 00000000 3c960408 00000000 64000000 ....<.......d...
What am I missing here?
thanks everyone again
Upvotes: 4
Views: 382
Reputation: 145829
"StackOverflow"
and "%s\n"
string literals are put in .rodata
(read only data ) section in most systems.
On UNIX, you can dump .rodata
section using the objdump command:
$ gcc tst.c
$ objdump -s -j .rodata a.out
As added by @FatalError in the comments, "%s\n"
is not visible with objdump in the example as gcc
optimizes a call to printf("%s\n",str)
by replacing it by a call to puts(str)
.
To see the "%s\n"
string literal in the objdump output, you can compile your program with gcc -fno-builtin
.
Upvotes: 6
Reputation: 753615
The standard doesn't define where the storage for "StackOverflow"
is located.
Often, it will be stored in the read-only text portion of your program; sometimes, it will be stored in the initialized data portion of your program. Neither of these is the stack; neither of these is the 'heap' (in the sense of dynamically allocated memory managed by malloc()
et al). The same comments and issues arise for the format string.
Upvotes: 4