0

Possible Duplicate:
C String literals: Where do they go?

Here is a piece of C code that I was asked to analyze in an interview.

int main() {
    char *ptr = "hello"; 
    return 0;
} 

Which part of the memory does the string "hello" get stored?

Community
  • 1
  • 1
sril
  • 53
  • 1
  • 7

1 Answers1

3

This is implementation-specific and not specified by the standard. You'd have to consult the documentation for your particular compiler to determine where it's placed.

Generally, compilers place string literals in a read-only data segment such as the code segment. This allows multiple different string literals to be encoded in the program using a single piece of memory, which can be shared. It's also why it's a Bad Idea to try to modify a string literal in-place, since this often triggers a segmentation fault due to writing to a read-only segment. This isn't guaranteed, but it's often implemented this way.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065