memory allocation
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 16

Thread: memory allocation

  1. #1
    Join Date
    Aug 2009
    Posts
    12

    memory allocation

    Dear All,

    If I write following statement, where will memory be allocated?
    If it is on heap, who will free the allocated memory?

    char* ptr = "hello";

    Thanks

  2. #2
    Join Date
    Jun 2009
    Posts
    5

    Re: memory allocation

    It's hard-coded into your program, stored with the executable code. You cannot free that memory from within your program, because it was allocated by the operating system when your program was loaded into memory. Every string literal exists within the code segment of your program in the computer's memory. If you want to be able to free the allocated memory, do this:

    Code:
    char* ptr = malloc(strlen("hello")+1);
    
    strcpy(ptr,"hello");
    
    free(ptr);
    Or, using new and delete:

    Code:
    char* ptr = new char[strlen("hello")+1];
    
    strcpy(ptr,"hello");
    
    delete ptr;

  3. #3
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Fairfax, VA
    Posts
    10,891

    Re: memory allocation

    Or using proper C++ techniques:
    Code:
    std::string str("hello");

  4. #4
    Join Date
    May 2009
    Posts
    2,413

    Re: memory allocation

    Quote Originally Posted by postiwala View Post
    If I write following statement, where will memory be allocated?
    If it is on heap, who will free the allocated memory?

    char* ptr = "hello";
    You should treat a String literal as you would a primitive literal.

    When you see,

    int i = 42;

    you don't wonder how and where 42 is allocated and deallocated.

    In the same fashion you shouldn't bother about "hello". That's the idea.
    Last edited by nuzzle; August 15th, 2009 at 07:36 PM.

  5. #5
    Join Date
    Feb 2009
    Posts
    326

    Re: memory allocation

    Given below are my views:
    a) memory is not allocated dynamically, the memory would be deallocated once ptr goes out of scope.
    b) since the memory is not allocated, you should not delete memory.


    Code from one of your other posts, shows that moment the pointer mystring goes out of scope, the memory of the char array is deallocated.
    Code:
    #include <iostream>
    using std :: cout;
    using std :: endl;
    
    char* getValue()
    {
            
        char* mystring = "hello";
        return (mystring);
         
    }
    
    int main()
    {
        char* ptr = getValue();
        ptr[2] = 'n';
    
        cout << "ptr = " << ptr << endl;
    
        return 0;
    }

  6. #6
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Fairfax, VA
    Posts
    10,891

    Re: memory allocation

    In the above code, the line
    Code:
        ptr[2] = 'n';
    is incorrect because it attempts to modify a string literal. This will probably cause a crash.

    For legacy reasons, string literals have type char*; however, in all modern code, you should treat them as if they have type const char*. Don't try to modify them.

  7. #7
    Join Date
    Feb 2009
    Posts
    326

    Re: memory allocation

    I don't think that program was trying to modify a string literal (pls correct me if i am wrong)

    It was trying to modify the char memory location which had been deallocated.

    given below is the modified version of the program which would work:

    Code:
    #include <iostream>
    using std :: cout;
    using std :: endl;
    
    char* getValue()
    {
        
        char* mystring = new char[6];
            
        mystring[0] = 'h';
        mystring[1] = 'e';
        mystring[2] = 'l';
        mystring[3] = 'l';
        mystring[4] = 'o';
        mystring[5] = '\0';
    
        return (mystring);
            
    }
    
    int main()
    {
        char* ptr = getValue();
        ptr[2] = 'n';
            
        cout << "ptr = " << ptr << endl;
    
        delete [] ptr;
            
        return 0;
    }

  8. #8
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Fairfax, VA
    Posts
    10,891

    Re: memory allocation

    Quote Originally Posted by Muthuveerappan View Post
    I don't think that program was trying to modify a string literal (pls correct me if i am wrong)

    It was trying to modify the char memory location which had been deallocated.
    That would be the case had the expression been:
    Code:
    char mystring[] = "hello";
    which would have created an array on the stack and copied the string literal into it.

    However, since it was
    Code:
    char *mystring = "hello";
    the returned pointer was actually directed at the string literal in static, read-only memory.

  9. #9
    Join Date
    Feb 2009
    Posts
    326

    Re: memory allocation

    you are right, thanks a lot !!

    I guess the below program illustrates that :
    if I was right, then the below would have worked, but it didn't.
    Like you said it should be treated like const char*, actually wish only const char* was allowed in this case.

    Code:
    #include <iostream>
    using std :: cout;
    using std :: endl;
    
    char* getValue()
    {
        
        char* mystring = "hello";
    
        mystring[0] = 'z';
    
        cout << mystring << endl;
            
        return (mystring);
         
    }
    
    int main()
    {
        char* ptr = getValue();
            
        return 0;
    }

  10. #10
    Join Date
    Aug 2009
    Posts
    12

    Re: memory allocation

    Dear All,

    Thank you very much for the replies.

    My question was probably not enough to explain my problem.
    Consider following code,

    #include <cstdlib>
    #include <iostream>

    using namespace std;

    char* getValue()
    {
    char* ptr = "hello";
    return ptr;
    }
    int getNumber()
    {
    int i = 32;
    return i;
    }

    int main(int argc, char *argv[])
    {

    char* ptr = getValue();
    cout << "ptr is :" << ptr <<endl;

    int i = getNumber();
    cout << "i is " << i <<endl;
    return 0;
    }


    Now If my understadning in not wrong, in case of getNumber() when i is returned its value is being copied.
    Similarly, in case of getValue() pointer is being copied and not the entire string..(Correct me if I am wrong).
    Tough in my test program, I always get output " ptr is : hello".

    Why is it so?
    (1). getValue returned pointer to a local memory and it should have been deleted as it went out of scope.
    (2). As I mentioned (1) didn't happen, it gave me feeling that there should be something different
    about handling memory of string literals.


    Please post your replies.

  11. #11
    Join Date
    Feb 2009
    Posts
    326

    Re: memory allocation

    I don't have answers to your question, but found the output of the following program interesting.

    the memory allocation of the string literal seems to be the same. I just feel the life time of this temporary memory address lasts till the end of the program (I could be completely wrong).

    Code:
    #include <iostream>
    using std :: cout;
    using std :: endl;
    
    void f1()
    {
        char *charP0 = "abcd";
        void *voidP0 = static_cast<void*>(charP0);
        cout << "charP0 = " << charP0 << "\tvoidP0 = " << voidP0 << endl;
    }
    
    
    int main()
    {
        system("clear");
    
        f1();
    
        char *charP1 = "abcd";
        void *voidP1 = static_cast<void*>(charP1);
    
        char *charP2 = "abcd";
        void *voidP2 = static_cast<void*>(charP2);
    
        char *charP3 = "abce";
        void *voidP3 = static_cast<void*>(charP3);
    
        cout << "charP1 = " << charP1 << "\tvoidP1 = " << voidP1 << endl
             << "charP2 = " << charP2 << "\tvoidP2 = " << voidP2 << endl
             << "charP3 = " << charP3 << "\tvoidP3 = " << voidP3 << endl;
    
        return(0);
    }
    Output:
    Code:
    charP0 = abcd	voidP0 = 0x1e49
    charP1 = abcd	voidP1 = 0x1e49
    charP2 = abcd	voidP2 = 0x1e49
    charP3 = abce	voidP3 = 0x1e69

    This thread has been a good learning for me, thanks for bringing it up. Still lots of unanswered questions. If only we had something like a destructor of char then we would know when it goes out of scope, can't think of a definitive way.

    small suggestion - Use code tags [code_] [/code_] (without the underscore)while posting code.
    Last edited by Muthuveerappan; August 17th, 2009 at 02:48 AM.

  12. #12
    Join Date
    May 2007
    Location
    Scotland
    Posts
    1,145

    Re: memory allocation

    Quote Originally Posted by postiwala View Post
    (1). getValue returned pointer to a local memory and it should have been deleted as it went out of scope.
    (2). As I mentioned (1) didn't happen, it gave me feeling that there should be something different
    about handling memory of string literals.
    Your function:
    Code:
    char* getValue()
    {
           char* ptr =  "hello";     
           return ptr;
    }
    returns a pointer to a string literal. A string literal does not have local scope but has static storage duration, therefore it will exist for as long as your program is alive for (or if it is in a dll, for as long as the dll is loaded for). This means that when your function returns, the string literal is still valid.

  13. #13
    Join Date
    May 2007
    Location
    Scotland
    Posts
    1,145

    Re: memory allocation

    Quote Originally Posted by Muthuveerappan View Post
    I just feel the life time of this temporary memory address lasts till the end of the program (I could be completely wrong).
    Regardless of where the a string literal is declared, the memory is allocated and initialised to the specified value before main() is called. The memory is not temporary, but has static storage duration and exists for the total life time of the program (or as mentioned before, the loaded life time of the dll if it is contained within a dll).

  14. #14
    Join Date
    Feb 2009
    Posts
    326

    Re: memory allocation

    Thanks a lot PredicateNormative, I still have some questions.

    Any reason why a char * (instead of const char*) is allowed to point to a string literal, as Lindley had previously stated it is a const string, so shouldn't be changed.

    Ideally shouldn't only a const char * be allowed, any reason why the compiler allows this ?

  15. #15
    Join Date
    Apr 1999
    Posts
    27,446

    Re: memory allocation

    Quote Originally Posted by Muthuveerappan View Post
    Thanks a lot PredicateNormative, I still have some questions.

    Any reason why a char * (instead of const char*) is allowed to point to a string literal,
    It is a holdover from the 'C' language.

    Regards,

    Paul McKenzie

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center