Thread: Question about memory allocation between methods

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    101

    Question about memory allocation between methods

    Maybe this has been answered before but my searches didn't find anything (but I'm not sure if I serched for it with the right key words).

    So my question is: If you have a method that creates a instance of a struct (like Data d) and then you fill the attributes with info from the user and in the end of the method you do return d can this be a problem?
    My point is when you return a structure created as said in method Data create() and then call it like
    Code:
    Data* pointer = (Data*)malloc(sizeof(Data));
    *pointer = create();
    will pointer be pointing to wherever d was stored or does it copy d to the place pointed to by pointer?

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Pointer will still be pointing to the same place -- you're not reassigning pointer, you are changing the value of what it points to. You should be fine here (unless data itself contains pointers -- you'll want to make sure those aren't pointing to local variables either).

  3. #3
    Technical Lead QuantumPete's Avatar
    Join Date
    Aug 2007
    Location
    London, UK
    Posts
    894
    You want something like this:
    Code:
    int main () {
        Data* pointer = (Data*)malloc(sizeof(Data));
        create (create);
        /* Blah */
    }
    
    void create (Data * d) {
       /* Fill (*d) with data */
    }
    Pass the pointer to your newly allocated memory to the create function, let it do its magic. The way you wrote in your post would overwrite the value of the pointer with whatever create() returns.

    QuantumPete
    "No-one else has reported this problem, you're either crazy or a liar" - Dogbert Technical Support
    "Have you tried turning it off and on again?" - The IT Crowd

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Memory allocation question
    By dakarn in forum C Programming
    Replies: 11
    Last Post: 12-01-2008, 11:41 PM
  2. A question related to dynamic memory allocation
    By spiit231 in forum C Programming
    Replies: 2
    Last Post: 03-11-2008, 12:25 AM
  3. Memory allocation and deallocation
    By Micko in forum C++ Programming
    Replies: 3
    Last Post: 08-19-2005, 06:45 PM
  4. Question regarding constructors and memory.....
    By INFERNO2K in forum C++ Programming
    Replies: 6
    Last Post: 05-25-2005, 11:30 AM
  5. Dynamic Memory Allocation for fstream (binary)
    By kuphryn in forum C++ Programming
    Replies: 2
    Last Post: 12-12-2001, 10:52 AM

Tags for this Thread