Home > OS >  Why are strings statically allocated in C?
Why are strings statically allocated in C?

Time:07-25

In C (at least) local string variables are allocated in the .rodata section or .data segment generally.

int main(){
    char string[] = "hello world!"; //this is allocated statically in the .rodata section not in the stack.
}

Why not store them on the stack, since it is a local variable? Will the string data be in memory for the full execution time? Is that not a waste of memory?

Edit: I am sorry, I checked with GDB and the string is loaded into the stack:

int main(){
       
    
    char string[] = " LLLLLLLLLLLLLLLLLLLLLLLLLLLLLL";
    
    printf("%s", string);
    
  
}
 0x004011fc < 99>:  movl   $0x4c4c4c20,-0x44(           
  • Related