Thread: address of constant

  1. #1
    Registered User
    Join Date
    May 2006

    address of constant

    Hello everyone,

    I have tried that even if I have multiple character pointer variables, if the content they pointed to are the same, they are allocated with the same value. So, I think from compiler point of view, the constant with the same content shares the single copy in memory?

    Here is my test program in Visual Studio 2005.

    #include <windows.h>
    int main (int argc, char** argv)
    	char* abc = "Hello";
    	char* abc2 = "Hello";
    	// the value (address) of abc is the same as abc2
    	return 0;

    thanks in advance,

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    Yes, that is correct.

    It is allowed to merge both copies of the same string into one, and make both pointers point at the same thing.
    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
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    United States
    Well George, abc points to read-only memory (string literals are read only, but they can be stored in writeable memory, like an array of characters). Therefore, one storage space for "Hello" should be sufficient since it is never moved or edited. Memory that you are allowed to write to is different, and may require several copies of the same object, like two integers that happen to be 4.

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Farncombe, Surrey, England
    Also beware that the compiler may well produce multiple strings if you use multiple source files in the project. So, you can't RELY on it being the same address [in fact, some compilers won't even merge the strings within a single source file].

    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. What does this do (Windows API)?
    By EVOEx in forum Windows Programming
    Replies: 4
    Last Post: 12-19-2008, 10:48 AM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  4. DX - CreateDevice - D3DERR_INVALIDCALL
    By Tonto in forum Game Programming
    Replies: 3
    Last Post: 12-01-2006, 07:17 PM
  5. load gif into program
    By willc0de4food in forum Windows Programming
    Replies: 14
    Last Post: 01-11-2006, 10:43 AM