malloc() inside functions 
Author Message
 malloc() inside functions

Hello-

     quick question about malloc()...

     consider.   char * function f()
                 {
                       char *ptr = malloc(sizeof(char) * 50);
                       return (ptr);
                 }

      is this acceptable? i'm wondering if the malloc storage is local
to the function or if the storage is global and the pointer is local.
i've found instances where i find the need to malloc() inside a
function and then use that pointer elsewhere i.e. in main() or in
another function calling f(). i know this works usually but i need to
know if i'm setting myself up for failure in the future... thanks.

mark. :-)



Wed, 02 Feb 2005 22:10:39 GMT  
 malloc() inside functions


Quote:
> Hello-

>      quick question about malloc()...

>      consider.   char * function f()
>                  {
>                        char *ptr = malloc(sizeof(char) * 50);
>                        return (ptr);
>                  }

>       is this acceptable?

Yes, it's valid code, but many would not do things this way
-- high possiblity of caller forgetting to release the memory.

Quote:
>i'm wondering if the malloc storage is local
> to the function or if the storage is global and the pointer is local.

The latter.  The allocated memory 'lives' until explicitly released
by a call to 'free()', or program termination.

Quote:
> i've found instances where i find the need to malloc() inside a
> function and then use that pointer elsewhere i.e. in main() or in
> another function calling f(). i know this works usually but i need to
> know if i'm setting myself up for failure in the future... thanks.

The above 'sets you up' for possiblities of bugs, yes, imo.  Have
the caller define and control the pointer.

#include <stdlib.h>

char *f(void)
{
    return malloc(50);

Quote:
}

int main()
{
    char *ptr = NULL;
    if(ptr = f(&ptr))
    {
        /* allocation succeeded */
        /* do stuff with 'ptr'

        free(ptr); /* release memory */
    }
    else
        /* allocation failed */

    return 0;

Quote:
}

Of course, with the limited context you gave, this example is
necessarily contrived, and a direct call to 'malloc()' would
probably be used above instead of 'wrapping' it in function 'f()'.

HTH,
-Mike



Wed, 02 Feb 2005 22:34:56 GMT  
 malloc() inside functions

Quote:

> Hello-

>      quick question about malloc()...

>      consider.   char * function f()
>                  {
>                        char *ptr = malloc(sizeof(char) * 50);
>                        return (ptr);
>                  }

>       is this acceptable? i'm wondering if the malloc storage is local
> to the function

This is perfectly acceptable (remember that the caller will have to check if
ptr is not NULL before using it).
malloc allocates from the "heap", which can be thought of as an area of
spare memory available to all the functions in your program.


Wed, 02 Feb 2005 22:29:24 GMT  
 malloc() inside functions

Quote:

>      consider.   char * function f()
>                  {
>                        char *ptr = malloc(sizeof(char) * 50);
>                        return (ptr);
>                  }

sizeof(char) is always 1.

When calling malloc(), I recommend using the sizeof operator on
the object you are allocating, not on the type.  For instance,
*don't* write this:

        int *x = malloc (sizeof (int) * 128); /* Don't do this! */

Instead, write it this way:

        int *x = malloc (sizeof *x * 128);

There's a few reasons to do it this way:

        * If you ever change the type that `x' points to, it's not
          necessary to change the malloc() call as well.

          This is more of a problem in a large program, but it's still
          convenient in a small one.

        * Taking the size of an object makes writing the statement
          less error-prone.  You can verify that the sizeof syntax is
          correct without having to look at the declaration.

Quote:
>       is this acceptable? i'm wondering if the malloc storage is local
> to the function or if the storage is global and the pointer is local.

Storage allocated with malloc() is "global", that is, it persists
as long as the program does.  Object `ptr' is local but the
storage that its value refers to is global.

Quote:
> i've found instances where i find the need to malloc() inside a
> function and then use that pointer elsewhere i.e. in main() or in
> another function calling f().

That's one of the useful features of malloc().
--
int main(void){char p[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.\
 \n",*q="kl BIcNBFr.NKEzjwCIxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+=strchr(p,*q++)-p;if(i>=(int)sizeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}


Thu, 03 Feb 2005 00:20:30 GMT  
 malloc() inside functions

Quote:

> char *f(void)

No parameters.

Quote:
> {
>     return malloc(50);
> }

> int main()
> {
>     char *ptr = NULL;
>     if(ptr = f(&ptr))

One argument.  Huh?
--
"Debugging is twice as hard as writing the code in the first place.
 Therefore, if you write the code as cleverly as possible, you are,
 by definition, not smart enough to debug it."
--Brian Kernighan


Thu, 03 Feb 2005 00:21:02 GMT  
 malloc() inside functions


Quote:

> > char *f(void)

> No parameters.

> > {
> >     return malloc(50);
> > }

> > int main()
> > {
> >     char *ptr = NULL;
> >     if(ptr = f(&ptr))

> One argument.  Huh?

Oops.  Should have been simply:

if(ptr = f())

Sorry about that.

-Mike



Thu, 03 Feb 2005 09:49:54 GMT  
 malloc() inside functions
:      quick question about malloc()...

:      consider.   char * function f()
:                  {
:                        char *ptr = malloc(sizeof(char) * 50);
:                        return (ptr);
:                  }

:       is this acceptable? i'm wondering if the malloc storage is local
: to the function or if the storage is global and the pointer is local.

Yes, this is acceptable.  malloc()'ed (and friends) memory is allocated to
the progam not the function which called malloc().  In order to *use* the
memory, you must always have a pointer pointing to that chunk of memory.
If you fail to do that you will have a condition which is called a
"memory leak". These are bad, very bad.

for example,

char *my_func( void )
{
    char *ret = malloc( 128 );
    return ret;

Quote:
}

Usage:

    char *p, *t;
    char data[] = "this is a character array.";

    t = data;

    p = my_func();

/* so far, OK.  your malloc()'ed memory is being kept
 * track of by pointer 'p'.
 */

  p = data;

/* oh, oh.  Here is a memory leak.  'p' was assigned
 * to point to the character array 'data'.  And in the
 * course of doing this, any reference to the malloc()'ed
 * memory allocated by my_func() is lost (even though
 * the memory is still allocated).  There is no way to
 * reference it now.
 */

When writing functions like this, I always document in the comments
describing the function that it is the calling function's responsibility
to free() the memory or pass it to another responsible function before
returning.

Good Luck,

Paul

--
Paul D. Boyle

North Carolina State University
http://www.xray.ncsu.edu



Sun, 06 Feb 2005 02:21:02 GMT  
 
 [ 7 post ] 

 Relevant Pages 

1. malloc inside function on variant parameter

2. Failure INSIDE malloc() ??

3. declaring functions inside other functions

4. Setting a pointer to a function, inside a function

5. Function inside another function?...

6. printing function name and arguments from inside a function

7. function to be defined inside other function

8. Function pointer to function inside class

9. function pointer inside a class

10. Debugging Inside a Function

11. Allocating memory inside a function

12. Pointers-to-functions inside a struct

 

 
Powered by phpBB® Forum Software