Thread: c string in memory.

  1. #1
    Registered User
    Join Date
    Sep 2004

    c string in memory.

    I have a question concerning what will happen to a string when I do like this:
    int main()
         char* text;
         text = "hello world";
         text = "this is a string";
         return 0;
    Does the string "hello world" remain in memory? And if it does, is it supposed to be considered a memory leak even though malloc is not involved?

    The reason I need to know this is because I want to try writing my own String class in c++, but since this is also a C question I'm posting it here.

    I'll be truly thankfull for any help!

  2. #2
    Registered User
    Join Date
    Oct 2006
    Miami, FL
    I'm pretty sure that you don't need to use free and that the memory will be freed when the program exits but maybe someone else can verify that. You could always just run a program like valgrind that checks to see if there are any memory leaks.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    If you didn't call malloc, then don't call free.

    Each malloc/calloc/realloc should be matched with exactly one free.

    > Does the string "hello world" remain in memory?
    String constants like those remain in memory as long as the program remains in memory.

    Compare with
    int i, j;
    int *p = &i;
    p = &j;
    You wouldn't do anything special with i, just because you made the pointer point at j.
    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.

  4. #4
    Registered User
    Join Date
    Sep 2004
    Ok, I see. Thank you both very much for answering!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pointer to String and memory status
    By 93 Years Old in forum C Programming
    Replies: 2
    Last Post: 07-23-2008, 06:40 AM
  2. To find the memory leaks without using any tools
    By asadullah in forum C Programming
    Replies: 2
    Last Post: 05-12-2008, 07:54 AM
  3. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  4. Calculator + LinkedList
    By maro009 in forum C++ Programming
    Replies: 20
    Last Post: 05-17-2005, 12:56 PM