You are on page 1of 13

Skip to content

 Tutorials
 Student
 Jobs
 Courses

Write
Come write articles for us and get featured

Practice
Learn and code with the best industry experts

Premium
Get access to ad-free content, doubt assistance and more!

Jobs
Come and find your dream job with us

o Geeks Digest
o Quizzes
o Geeks Campus
o Gblog Articles
o IDE
o Campus Mantri


 My Profile  Edit Profile
 My Courses  Go Premium
  Logout
 Home
 Courses

o Practice DS & Algo.
o Algorithms
o Analysis of Algorithms
o Data Structures
o Interview Corner
o Languages
o ISRO CS
o GATE
o CS Subjects
o Web Technologies
o School Learning
o Mathematics
o Maths Notes (Class 8-11)
o NCERT Solutions
o RD Sharma Solutions
o UGC NET CS
o Student
o Jobs
 GBlog
 Puzzles
 What's New ?
 Change Language
Related Articles

Related Articles
 Storage for Strings in C
 C++ string class and its applications
 Pointers in C and C++ | Set 1 (Introduction, Arithmetic and Array)
 References in C++
 Object Oriented Programming in C++
 auto_ptr, unique_ptr, shared_ptr, weak_ptr
 Pointers in C and C++
 Pointers in C/C++ with Examples
 C++ Classes and Objects
 Access Modifiers in C++
 Inheritance in C++
 Virtual Functions and Runtime Polymorphism in C++ | Set 1 (Introduction)
 Virtual Function in C++
 Polymorphism in C++
 Encapsulation in C++
 Abstraction in C++
 Structure vs class in C++
 Can a C++ class have an object of self type?
 Why is the size of an empty class not zero in C++?
 Static data members in C++
 Some interesting facts about static member functions in C++
 Friend class and function in C++
 Local Classes in C++
 Nested Classes in C++
 Simulating final class in C++
 Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
 Tree Traversals (Inorder, Preorder and Postorder)
 What is Memory Leak? How can we avoid?
 Practice for cracking any coding interview
 Must Do Coding Questions Company-wise

Storage for Strings in C


 Difficulty Level : Medium
 Last Updated : 16 Jul, 2021
In C, a string can be referred to either using a character pointer or as a character array. 
Strings as character arrays  
 C

char str[4] = "GfG"; /*One extra for string terminator*/

/*    OR    */

char str[4] = {‘G’, ‘f’, ‘G’, '\0'}; /* '\0' is string terminator */

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. 
 C

char *str  =  "GfG";  

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. 

 C

char *str;

int size = 4; /*one extra for ‘\0’*/

str = (char *)malloc(sizeof(char)*size);

*(str+0) = 'G'; 

*(str+1) = 'f';  

*(str+2) = 'G';  

*(str+3) = '\0';  

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. 
 C

int main()

 char *str; 

 str = "GfG";     /* Stored in read only part of data segment */

 *(str+1) = 'n'; /* Problem:  trying to modify read only memory */

 getchar();

 return 0;
}

The below program works perfectly fine as str[] is stored in writable stack segment. 

 C

int main()

 char str[] = "GfG";  /* Stored in stack segment like other auto variables */

 *(str+1) = 'n';   /* No problem: String is now GnG */

 getchar();

 return 0;

Below program also works perfectly fine as data at str is stored in writable heap
segment. 

 C

int main()

  int size = 4;

  

  /* Stored in heap segment like other dynamically allocated things */

  char *str = (char *)malloc(sizeof(char)*size);


  *(str+0) = 'G'; 

  *(str+1) = 'f';  

  *(str+2) = 'G';    

  *(str+3) = '\0';  

  *(str+1) = 'n';  /* No problem: String is now GnG */

   getchar();

   return 0;

}     

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() 
 C

char *getString()

  char *str = "GfG"; /* Stored in read only part of shared segment */

  

  /* No problem: remains at address str after getString() returns*/

  return str;  

}     

  

int main()
{

  printf("%s", getString());  

  getchar();

  return 0;

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()  

 C

char *getString()

  int size = 4;

  char *str = (char *)malloc(sizeof(char)*size); /*Stored in heap segment*/

  *(str+0) = 'G'; 

  *(str+1) = 'f';  

  *(str+2) = 'G';

  *(str+3) = '\0';  

    

  /* No problem: string remains at str after getString() returns */    

  return str;  

}     
int main()

  printf("%s", getString());  

  getchar();

  return 0;

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. 

 C

char *getString()

  char str[] = "GfG"; /* Stored in stack segment */

  

  /* Problem: string may not be present after getString() returns */

  /* Problem can be solved if write static before char, i.e. static char str[] =
"GfG";*/

  return str; 

}     

int main()

  printf("%s", getString());  
  getchar();

  return 0;

Please write comments if you find anything incorrect in the above article, or you want
to share more information about the storage of strings
 
Want to learn from the best curated videos and practice problems, check out the C
Foundation Course for Basic to Advanced C.

Like138
Next
C++ string class and its applications
ADVERTISEMENT BY ADRECOVER

RECOMMENDED ARTICLES
Page :

1
2
3
C | Storage Classes and Type Qualifiers | Question 6
09, Feb 13

C | Storage Classes and Type Qualifiers | Question 7


09, Feb 13

C | Storage Classes and Type Qualifiers | Question 8


09, Feb 13

C | Storage Classes and Type Qualifiers | Question 19


09, Feb 13

C | Storage Classes and Type Qualifiers | Question 12


15, Feb 13

Problem Solving on Storage Classes and Scoping of Variables


13, Feb 18

Will we ever run out of cloud storage?


09, May 18

Storage of integer and character values in C


25, Jul 18

C | Storage Classes and Type Qualifiers | Question 19


09, Feb 13

C | Storage Classes and Type Qualifiers | Question 19


09, Feb 13

C | Storage Classes and Type Qualifiers | Question 9


09, Feb 13

C | Storage Classes and Type Qualifiers | Question 19


26, Feb 13

C | Storage Classes and Type Qualifiers | Question 19


06, Mar 13

C | Storage Classes and Type Qualifiers | Question 19


06, Mar 13

Storage Classes in C
18, Jul 15

C | Storage Classes and Type Qualifiers | Question 1


09, Feb 13
C | Storage Classes and Type Qualifiers | Question 3
09, Feb 13

C | Storage Classes and Type Qualifiers | Question 11


09, Feb 13

C | Storage Classes and Type Qualifiers | Question 14


26, Feb 13

C | Storage Classes and Type Qualifiers | Question 17


07, Mar 13

C | Storage Classes and Type Qualifiers | Question 18


06, Sep 13

C | Storage Classes and Type Qualifiers | Question 19


09, Sep 13

Count of strings that become equal to one of the two strings after one
removal
14, Jan 19

C function to Swap strings


06, Mar 10

Article Contributed By :

GeeksforGeeks
Vote for difficulty
Current difficulty : Medium
EasyNormalMediumHardExpert
Improved By :
 Akanksha_Rai
 gunturupruthvi27
 kanchanchauhankc
Article Tags :
 C Array and String
 Articles
 C Language
Improve Article
Report Issue
ADS BY ADRECOVER

WHAT'S NEW

Ad free experience with GeeksforGeeks Premium


View Details

DSA Self Paced Course


View Details

DSA Live Classes for Working Professionals


View Details

ADS BY ADRECOVER

MOST POPULAR IN ARTICLES


 find command in Linux with examples
 SQL | Join (Inner, Left, Right and Full Joins)
 Commonly Asked Data Structure Interview Questions | Set 1
 Analysis of Algorithms | Set 1 (Asymptotic Analysis)
 SQL | Views

ADS BY ADRECOVER

MOST VISITED IN C LANGUAGE


 Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
 std::sort() in C++ STL
 Arrays in C/C++
 Bitwise Operators in C/C++
 Converting Strings to Numbers in C/C++

ADS BY ADRECOVER
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.

Load Comments

ADVERTISEMENT BY ADRECOVER
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org

 Company
 About Us
 Careers
 Privacy Policy
 Contact Us
 Copyright Policy
 Learn
 Algorithms
 Data Structures
 Languages
 CS Subjects
 Video Tutorials
 Practice
 Courses
 Company-wise
 Topic-wise
 How to begin?
 Contribute
 Write an Article
 Write Interview Experience
 Internships
 Videos
@geeksforgeeks , Some rights reserved

You might also like