Hi everyone.. Suppose i have a function :
void foo(int ind,float **ptr1,float **ptr2) that allocates memory using malloc .. - double pointers are much more in reality-
I want to use this pointers in other functions too, but when i call them(functions) in main() .. memory leak message appears ..
Is there a way to stop this without the usage of gloabal variables..
To be more understanding here s an example of a older post :
void foo( char * ptr)
{
ptr = malloc(255); // allocate some memory
strcpy( ptr, "Hello World");
.
}
int main()
{
char *ptr = 0;
foo( ptr );
printf("%s\n", ptr);
free(ptr);
return 0;
}
The answer
void foo( char * ptr)
"The problem is that ptr is a local object which has scope only within the function foo(). So the memory allocated with malloc() will be tossed into the bit bucket as soon as foo() returns to main(), and that will cause a memory leak. Inside function main() the value of ptr will still be 0 after foo() returns and the next line, printf(), will probably crash because the second argument (ptr) is a NULL pointer. "
So in the above example suppose that we have more than one double pointers in the function.. and we can t use return or gloabal variables