4

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

2 Answers 2

6

"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.

Sign up to request clarification or add additional context in comments.

2 Comments

On linux (and similar) systems you can objdump -s -j .rodata on your binary to see it. Also, if you use gcc you won't find "%s\n" because gcc optimizes that pattern into a call to puts().
@FatalError I wrote the objdump command in the same time as your comment:) good point for puts I edit my answer to add it.
4

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.

1 Comment

As @ ouah and @FatalError suggested, I was able to see "Stackoverflow" and "%s" by doing objdump -s -j .rodata a.out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.