I need help with malloc()
inside another function.
I\'m passing a pointer and size to the fu
As mentioned in the other answers, we need a pointer to the pointer. But why?
We need to pass the value by a pointer in order to be able to modify the value. If you want to modify an int
, you need to pass it by the int*
.
In this question, the value we want to modify is a pointer int*
(pointer changed from NULL
to the address of the allocated memory), so we need to pass a pointer to the pointer int**
.
By doing followed, pInt
inside foo(int*)
is a copy of the argument. When we allocate memory to the local variable, the one in the main()
is intact.
void foo(int* pInt)
{
pInt = malloc(...);
}
int main()
{
int* pInt;
foo(pInt);
return 0;
}
So we need a pointer to pointer,
void foo(int** pInt)
{
*pInt = malloc(...);
}
int main()
{
int* pInt;
foo(&pInt);
return 0;
}
If you want your function to modify the pointer itself, you'll need to pass it as a pointer to a pointer. Here's a simplified example:
void allocate_memory(char **ptr, size_t size) {
void *memory = malloc(size);
if (memory == NULL) {
// ...error handling (btw, there's no need to call free() on a null pointer. It doesn't do anything.)
}
*ptr = (char *)memory;
}
int main() {
char *data;
allocate_memory(&data, 16);
}
The only way I could get pointer to a pointer solution to work for a similar problem I was having for this function
BOOL OpenBitmap2 ( LPCTSTR pszFileName, char** pszBMPFile)
Was by assigning a temporary pointer to store the address
char* BMPFile;
{ BMPFile = (char*)GlobalAlloc(GPTR, dwFileSize + 1); // allocate storage using GlobalAlloc + 1 for null term string
then reassigning it
{* pszBMPFile = BMPFile; return (0);} // Error = False
Any comment on why using "* pszBMPFile" directly with GlobalAlloc didn't work would be appreciated. I answered my own question. I forgot to carry the "*" through with pszBMPFile in the other lines of code. Good lessons from all the contributors. Many thanks.