August 6th, 2010, 04:24 AM
malloc inside a function
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.
unsigned char *ptr;
unsigned char temp; // 1024 is larger than memSize
memcpy(temp, ptr, memSize);
void foo(unsigned char *ptr, int memSize)
*memSize = someotherfunction();
ptr = (unsigned char *)malloc(*memSize)
August 6th, 2010, 04:31 AM
Re: malloc inside a function
Yes it is possible. The problem you're having is that you are changing the value of a temporary within a function.
Originally Posted by galapogos
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.
Just like this code won't work:
I tried the following code, but doesn't seem to work.
void foo(int x)
x = 10;
int p = 0;
foo( p );
// p is still 0. Why isn't it 10?
Click Here to Expand Forum to Full Width
This is a CodeGuru survey question.