Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ string literal data type storage

Tags:

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?

like image 395
skydoor Avatar asked Feb 24 '10 17:02

skydoor


People also ask

Where are string literals stored in memory?

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.

How many bytes is a string literal in C?

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.

Are string literals stored in read only memory?

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 .

How many bytes is a string literal?

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.


2 Answers

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"; 
like image 92
Hassan Syed Avatar answered Oct 06 '22 11:10

Hassan Syed


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:

ELF Layout

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.

like image 24
David Pfeffer Avatar answered Oct 06 '22 11:10

David Pfeffer