void f() { char *c = "Hello World!" }
Where is the string stored? What's the property of it? I just know it is a constant, what else? Can I return it from inside of the function body?
Strings are stored on the heap area in a separate memory location known as String Constant pool. String constant pool: It is a separate block of memory where all the String variables are held. String str1 = "Hello"; directly, then JVM creates a String object with the given value in a String constant pool.
ANSI compatibility requires a compiler to accept up to 509 characters in a string literal after concatenation. The maximum length of a string literal allowed in Microsoft C is approximately 2,048 bytes.
Modifying a string literal frequently results in an access violation because string literals are typically stored in read-only memory. (See undefined behavior 33.) Avoid assigning a string literal to a pointer to non- const or casting a string literal to a pointer to non- const .
like int takes 4 bytes how much does string occupy in memory? A char, by definition, takes up one byte. A string literal is implicitly null-terminated, so it will take up one more byte than the observable number of characters in the literal.
it is packaged with your binary -- by packaged I mean hard-wired, so yes you can return it and use it elsewhere -- you won't be able to alter it though, and I strongly suggest you declare it as:
const char * x = "hello world";
The string is stored in the data area of the program. This is completely compiler, executable format, and platform dependent. For example, an ELF binary places this in a different location than a Windows executable, and if you were compiling for an embedded platform this data might be stored in ROM instead of RAM.
Here's an illustration of the layout of the ELF format:
Your string data would most likely be found in the .data
or .text
sections, depending on compiler.
You can certainly return it from inside the function body. Just check with your implementation to verify that it is random access, as many implementations won't let you overwrite it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With