Thread: How C programs store string literals?

  1. #1
    Registered User
    Join Date
    Apr 2011
    Posts
    33

    How C programs store string literals?

    The output of the following program:

    Code:
    int main(){
        int x = "test";
        int y = "test";
    
        printf("%u %u\n",x,y);
    
        return 0;
    }
    Will be the same memory address printed twice. In other words, you could do (if "test"=="test") and you would get a true as result.

    Does this mean that whenever you invoke a string literal the program will check if the same string has been stored previously, and in positive case it will just return a pointer to that same string instead of allocating memory for a new one?

  2. #2
    Registered User
    Join Date
    Sep 2007
    Posts
    1,012
    Does this mean that whenever you invoke a string literal the program will check if the same string has been stored previously, and in positive case it will just return a pointer to that same string instead of allocating memory for a new one?
    No. A compiler is free to do this, but it does not have to.

  3. #3
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by envec83 View Post
    The output of the following program:

    Code:
    int main(){
        int x = "test";
        int y = "test";
    
        printf("%u %u\n",x,y);
    
        return 0;
    }
    Will be the same memory address printed twice. In other words, you could do (if "test"=="test") and you would get a true as result.

    Does this mean that whenever you invoke a string literal the program will check if the same string has been stored previously, and in positive case it will just return a pointer to that same string instead of allocating memory for a new one?

    What Cas says...plus "usually"...

    Older compilers kept them separate because you were allowed to modify them.
    Newer "optimizing" compilers will most often match them up to the same address and you are not allowed to modify them.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. where the "String literals" store in ?
    By liyanhong in forum C Programming
    Replies: 13
    Last Post: 06-15-2010, 04:03 AM
  2. help! string literals
    By cakestler in forum C Programming
    Replies: 16
    Last Post: 02-05-2009, 11:41 AM
  3. Can't add string literals.
    By computerquip in forum C++ Programming
    Replies: 3
    Last Post: 11-13-2008, 01:20 AM
  4. UTF-8 string literals
    By pdc in forum C Programming
    Replies: 6
    Last Post: 07-28-2005, 02:52 PM
  5. String Literals
    By Trauts in forum C++ Programming
    Replies: 8
    Last Post: 05-17-2003, 08:39 PM