In C, a string can be referred to either using a character pointer or as a character array.
Strings as character arrays
When strings are declared as character arrays, they are stored like other types of arrays in C. For example, if str is an auto variable then string is stored in stack segment, if it’s a global or static variable then stored in data segment, etc.
Strings using character pointers
Using character pointer strings can be stored in two ways:
1) Read only string in a shared segment.
When a string value is directly assigned to a pointer, in most of the compilers, it’s stored in a read-only block (generally in data segment) that is shared among functions.
In the above line “GfG” is stored in a shared read-only location, but pointer str is stored in a read-write memory. You can change str to point something else but cannot change value at present str. So this kind of string should only be used when we don’t want to modify string at a later stage in the program.
2) Dynamically allocated in heap segment.
Strings are stored like other dynamically allocated things in C and can be shared among functions.
Let us see some examples to better understand the above ways to store strings.
Example 1 (Try to modify string)
The below program may crash (gives segmentation fault error) because the line *(str+1) = ‘n’ tries to write a read only memory.
The below program works perfectly fine as str is stored in writable stack segment.
Below program also works perfectly fine as data at str is stored in writable heap segment.
Example 2 (Try to return string from a function)
The below program works perfectly fine as the string is stored in a shared segment and data stored remains there even after return of getString()
The below program also works perfectly fine as the string is stored in heap segment and data stored in heap segment persists even after the return of getString()
But, the below program may print some garbage data as string is stored in stack frame of function getString() and data may not be there after getString() returns.
Please write comments if you find anything incorrect in the above article, or you want to share more information about the storage of strings