Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In which data segment is the C string stored?

Tags:

People also ask

Where are C strings stored?

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 the string is stored in stack segment, if it's a global or static variable then stored in data segment, etc.

What data type is string in C?

Overview. The C language does not have a specific "String" data type, the way some other languages such as C++ and Java do. Instead C stores strings of characters as arrays of chars, terminated by a null byte.

Where is string data stored?

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.

What are data segments in C?

A data segment is a portion of the virtual address space of a program, which contains the global variables and static variables that are initialized by the programmer. Note that, the data segment is not read-only, since the values of the variables can be altered at run time.


I'm wondering what's the difference between char s[] = "hello" and char *s = "hello".

After reading this and this, I'm still not very clear on this question.


As I know, there are five data segments in memory, Text, BSS, Data, Stack and Heap.

From my understanding,

in case of char s[] = "hello":

  1. "hello" is in Text.
  2. s is in Data if it is a global variable or in Stack if it is a local variable.

  3. We also have a copy of "hello" where the s is stored, so we can modify the value of this string via s.

in case of char *s = "hello":

  1. "hello" is in Text.
  2. s is in Data if it is a global variable or in Stack if it is a local variable.
  3. s just points to "hello" in Text and we don't have a copy of it, therefore modifying the value of string via this pointer should cause "Segmentation Fault".

Am I right?