Freeing memory allocated inside a function 
Author Message
 Freeing memory allocated inside a function

I have a function that returns a pointer to a struct

struct A {
 int    size ;
 int    *vector;

Quote:
}

strptr *func(strptr1,str2ptr)
strptr *strptr1;
strptr *strptr2;
{
   strptr *tmpptr;
...
   tmpptr->size = strptr1->size;
   tmpptr->vector = (int *)malloc(tmpptr->size*sizeof(struct );
...

  return tmpptr;

Quote:
}

This works fine. My question is since I am allocating both the structure
and the "vector" inside the function do I need to "free" the space
before exiting the function??

Please respond by email.

Thanks,

Sudhakaran Ram



Mon, 24 May 1999 03:00:00 GMT  
 Freeing memory allocated inside a function



Quote:
> I have a function that returns a pointer to a struct

> struct A {
>  int       size ;
>  int       *vector;
> }

> strptr *func(strptr1,str2ptr)
> strptr *strptr1;
> strptr *strptr2;
> {
>    strptr *tmpptr;
> ...
>    tmpptr->size = strptr1->size;
>    tmpptr->vector = (int *)malloc(tmpptr->size*sizeof(struct );
> ...

>   return tmpptr;
> }

> This works fine. My question is since I am allocating both the structure
> and the "vector" inside the function do I need to "free" the space
> before exiting the function??

If you are finished with the allocated objects, free when you exit.
Regardless of when you finish using them, you must have one free()
of the exact pointer you allocated memory for, for each corresponding
malloc() in your program, or you will develop a memory leak.

Since we do not know how you plan to use your data structures, any
'yes' or 'no' answer to your question has no value.

The C FAQ by Steve Summit talks at length about memory allocation.
It explains this situation eloquently.  If you have not already
done so, please read it.



Mon, 24 May 1999 03:00:00 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. allocating memory in one function and freeing it with another function

2. Allocating memory inside a function

3. Help with Re-Allocating Memory inside a structure

4. how to allocate a pointer with changing memory size inside a program

5. What is the proper way to allocate and free memory in this instance

6. freeing allocated memory from included files

7. freeing the memory allocated by calloc

8. newbie malloc problem: free memory allocated to structures

9. problem allocating/freeing memory of multidimensional arrays

10. doubt - freeing the memory allocated by calloc

11. Non-allocated memory- is it freed?

12. freeing allocated memory...

 

 
Powered by phpBB® Forum Software