Re: malloc() for struct member



On 5 Oct 2005 20:06:15 -0700, "googler" <pinaki_m77@xxxxxxxxx> wrote:

>Hello, I have a very simple question that I'm a bit confused about
>right now. Is it OK to allocate memory by malloc() or calloc() for a
>struct member and then call free() on it? For example, I have the code
>below.
>
>struct mystruct {
> int a;
> char *b;
> int c;
>};
>
>struct mystruct myobject;
>
>myobject.b = (char *)malloc(50);

Don't cast the return from malloc. It doesn't help and may cause the
compiler to suppress a diagnostic you really want to see.
>...
>...
>free(myobject.b);

This is how you would avoid a memory leak. What prompted the
question?

>
>Is the above code OK, or is there any potential problem with it?
>
>Thanks!


<<Remove the del for email>>
.



Relevant Pages

  • Re: Basic Pointer Question...
    ... I coded a function to allocate memory and i am passing a pointer to the function. ... In addition, as malloc() is hidden within a function, freecan be easily forgotten. ...
    (comp.lang.c)
  • Re: Newbie needs help with pointers/memory allocation
    ... to int), allocate memory for pointer and data, and print some output. ... casting the result of malloc() does not invoke undefined behavior. ...
    (comp.lang.c)
  • Re: malloc() for struct member
    ... Is it OK to allocate memory by malloc() or callocfor a ... > int a; ... > struct mystruct myobject; ... > Is the above code OK, or is there any potential problem with it? ...
    (comp.lang.c)
  • Re: [OT] C programming, variable size array
    ... If you want a dynamically sized array in C, ... using malloc() and friends. ... int main{ ... It would be better to allocate memory in chunks, or better yet, do ...
    (Debian-User)
  • malloc() for struct member
    ... Is it OK to allocate memory by malloc() or calloc() for a ... struct mystruct myobject; ...
    (comp.lang.c)