C++ string literal data type storage

青春壹個敷衍的年華 提交于 2019-11-27 04:47:59

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"; 
David Pfeffer

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.

§2.14.15 String Literals, Section 7

A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration.

It is generally stored in the read only section of memory and has static storage allocation.

Performing operations like c[0] = 'k' etc invokes Undefined Behavior.

Can I return it from inside of the function body?

Yes!

It has static storage duration, so it exists throughout the life of the program. Exactly where the compiler/linker put initialized data varies. Returning a pointer to it from a function is fine, but be sure you return a char const * -- writing to the string causes undefined behavior.

It's implementation defined. Most of the time that would be stored in a string table with all the other strings in your program. Generally you can treat it like a global static const variable except it's not accessible outside your function.

The string literals are stored on DATA segment and allocated at compile time. This helps to assign same string literals to multiple variables without creating copies of string.

e.g char * str="hello";

The str is char pointer, having address of char h, while "hello" is stored in data segment and cannot be altered. Trying to alter it will generate Segmentation fault.

While assigning a char array string literal creates a copy of string on stack.

i.e char str[]="hello";

"hello" is copied to stack (appended by null character) and str points to character 'h' in stack.

It's been a while since I played with C++, but I remember I (self taught) had a load of problems with strings (well, ok, character arrays...).

If you're going to be modifying their value at all, be sure to use the new and delete keywords... Something along these lines...

char *strText = new char[10]; /* Do something ... ... ... */ delete [] strText; 

Martin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!