malloc inside a function
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: malloc inside a function

  1. #1
    Join Date
    Feb 2005
    Posts
    325

    malloc inside a function

    Hi,

    I'm trying to pass a pointer to a function, and then have the function allocate some memory for that pointer. Is this possible?

    I tried the following code, but doesn't seem to work. Once I return from the function, the pointer seems to be void. The program crashes when I try to access it in main with memcpy() or some other function.

    Code:
    int main()
    {
      unsigned char *ptr;
      int memSize;
      unsigned char temp[1024]; // 1024 is larger than memSize
    
      foo(ptr, &memSize);
      memcpy(temp, ptr, memSize);
    }
    
    void foo(unsigned char *ptr, int memSize)
    {
      *memSize = someotherfunction();
      ptr = (unsigned char *)malloc(*memSize)
    }

  2. #2
    Join Date
    Apr 1999
    Posts
    27,418

    Re: malloc inside a function

    Quote Originally Posted by galapogos View Post
    Hi,

    I'm trying to pass a pointer to a function, and then have the function allocate some memory for that pointer. Is this possible?
    Yes it is possible. The problem you're having is that you are changing the value of a temporary within a function.

    When you pass a parameter by value, the function makes a temporary copy. When that function returns, that temporary is gone. A pointer is nothing but a value you're passing, and the same rules apply.

    To change a parameter value and have it reflect back to the caller, you either pass a pointer to the variable, or a reference to the variable. So you either pass a pointer to the pointer, or a reference to the pointer.
    I tried the following code, but doesn't seem to work.
    Just like this code won't work:
    Code:
    void foo(int x)
    {
        x = 10;
    }
    
    int main()
    {
       int p = 0;
       foo( p );
       // p is still 0.  Why isn't it 10?
    }
    Same principle.

    Regards,

    Paul McKenzie

Posting Permissions

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


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center