Thread: storage location for a string initialized to char pointer

  1. #1
    Registered User
    Join Date
    Feb 2014
    Posts
    54

    Cool storage location for a string initialized to char pointer

    When we store a string using char pointer, then where memory will be allocated for string.


    If we initialize a char pointer as shown below within a function.
    Code:
    char *cp = "ABC";
    then memory for cp will be allocated in stack as it is local, but where memory will be allocated for "ABC" string.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,665
    > then memory for cp will be allocated in stack as it is local, but where memory will be allocated for "ABC" string.
    String constants are stored in some kind of initialised memory that is set up when the program is loaded.

    In Linux/gcc for example, string constants end up in a section of memory called ".rodata" (read-only data).
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Feb 2014
    Posts
    54
    Thanks for the info.

  4. #4
    Registered User
    Join Date
    Feb 2014
    Posts
    54
    In the following program where memory will be allocated for the string "ABC".

    Code:
    int lenstr(char *s)
    {
        int len;
        while(*s)
            len++;
    
    
        return len;
    }
    
    int main()
    {
        int i;
        i=lenstr("ABC");
        return 0;
    }

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,665
    Same answer as before.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 12-02-2012, 05:25 AM
  2. Replies: 6
    Last Post: 11-19-2012, 01:26 PM
  3. lookup tables storage location
    By ali.franco95 in forum C Programming
    Replies: 5
    Last Post: 09-12-2011, 09:47 AM
  4. C++ storage location for various variables
    By sed_y in forum C++ Programming
    Replies: 14
    Last Post: 07-18-2011, 07:55 PM
  5. How tell if pointer has been initialized?
    By 6tr6tr in forum C++ Programming
    Replies: 6
    Last Post: 04-11-2008, 04:50 PM

Tags for this Thread