Re: a quick malloc question

From: Pascal Bourguignon (spam_at_thalassa.informatimago.com)
Date: 09/27/03


Date: 27 Sep 2003 08:14:54 +0200


drejcicaREMOVE@volja.net writes:
> Hello,
> if I use a variable multiple times within my program, is it better to
> declare it as a pointer and malloc() it every time (if the value of the
> variable is changed many times)?

What do you mean "use"?

Note that programs don't work on variables, but on the data stored in
the variables (in memory denoted by 'variables').

The variables only serve to refer to the data the program use.

So the question is whether you need this data either:

    - during the execution of a single procedure,

    - during the execution of various imbricated procedures (one
      calling the others),

    - during the execution of various independant procedures.

    - etc.

In the first case, the best is to use a local variable, (automatic
variable in C parlance), that is, a variable that is allocated
automatically at the entry of the procedure and that is deallocated
automatically at the exit of this procedure. Of course, the data
stored in this data is available only during the execution of this
procedure.

An exception of this case is if this data is very big or dynamical in
size, then you'll want to allocate on the heap rather than on the
stack as it's done for automatic variables, and you'll free it's
memory at the end of the procedure.

    void procedure(void)
    {
        int variable; /* the memory for variable is automatically allocated */
        variable=DATA;
        /* do something with variable */
        
        /* at the end, the memory for variable is automatically deallocated. */
    }

    void procedure(void)
    {
        int* variable;
        /* here, we allocate the variable yourself on the heap, since it's
           a very big array: */
        variable=(int*)malloc(sizeof(*variable)*100000);
        for(i=0;i<100000;i++){ variable[i]=i; }
        /* do something with variable */
        
        /* at the end, we free yourself the memory of variable */
        free(variable);
    }

        
In the second case, it's the same as in the first. Only, in C, since
there is no lexically imbricated functions, you have to pass a
reference to the variable as argument.

    void procedure(void)
    {
        int variable; /* the memory for variable is automatically allocated */
        variable=DATA;
    
        do_something_with(&variable);
        
        /* at the end, the memory for variable is automatically deallocated. */
    }

    void procedure(void)
    {
        int* variable;
        /* here, we allocate the variable yourself on the heap, since it's
           a very big array: */
        variable=(int*)malloc(sizeof(*variable)*100000);
        for(i=0;i<100000;i++){ variable[i]=i; }
        
        do_something_with(variable); /* this is already a reference! */
        
        /* at the end, we free yourself the memory of variable */
        free(variable);
    }

In the last case, when you need to use the same data from different
independent procedures, it's usually better to allocate the storage
for this data dynamically (or in some special cases, as static global
variables).

    typedef struct { /* ... */ } data_t;

    void fun1(data_t** data)
    {
        /* here we allocate and initialize the data */
        (*data)=(data_t*)malloc(sizeof(**data));
        (*data)->field1=0;
        (*data)->field2=0;
    }

    int fun2(data_t* data)
    {
        /* here, we use the data */
        return(data->field1 + data->field2);
    }

    void fun3(data_t* data)
    {
        /* here we free the storage for data */
        free(data);
    }
       
    void fun4(void)
    {
        data_t* data;
        fun1(&data);
        fun2(data);
        fun3(data); /* after fun3, we cannot use *data anymore */
    }

> If it's not a pointer, does it lead to a memory leak?

What leads to memory leaks is to allocate a memory block and never
deallocating, while forgetting all reference to this memory block.

If you worry about memory leaks, the best thing would be to use a
garbage collector. See: http://www.hpl.hp.com/personal/Hans_Boehm/gc/

> However, if it is a pointer, I can use one and the same
> address every time I change its value.

A pointer is nothing. What is important, is not the variable or the
type of the variable, but the data and the type of the data. Of
course, it's important to declare the type of the variable to be
exactly the type of the data you have, but first think about your data.

A pointer is only a reference to your data. A variable is the same
thing. The difference is that the variable is something declared in
the source and manipulated by the compiler at compilation time, while
the pointers are created and manipulated by your program at run-time.

You can have pointers to data stored in the static area, data stored
on the stack (in an automatic variable) or data stored in the heap
(allocated dynamically). And you can have variables that refer to
data stored in the static area or stored on the stack (but in C, not
on the heap; in other languages some variables may be stored on the
heap too).

    static int var1=1;

    void fun9(void)
    {
        int var2=2;
        int* var3=(int*)malloc(sizeof(*var3));

        int* p1=&var1;
        int* p2=&var2;
        int* p3=&var3;

        (*var3)=3;

        /* So now, we have three pointers: p1, p2, p3, one pointing to
           the data of a static variable, the other to the data of an
           automatic variable, and the last, to the data of a dynamic
           variable. */
        printf(" *p1=%d *p2=%d *p3=%d\n",*p1,*p2,*p3);
        printf("var1=%d var2=%d *var3=%d\n",var1,var2,*var3);
    }

-- 
__Pascal_Bourguignon__
http://www.informatimago.com/
Do not adjust your mind, there is a fault in reality.


Relevant Pages

  • Re: Is There Any Reason to Even Use VC++ Anymore?
    ... If, for another reason, the calling function needs to allocate memory, ... It does this by taking a pointer to a ball object ...
    (microsoft.public.dotnet.languages.vc)
  • Re: Pointer to the out of scope local variables
    ... of a pointer, and jumped to the conclusion that you allocated the memory ... In this particular case the funtion buildPoint would allocate ... If the caller ...
    (microsoft.public.vc.language)
  • Re: Memory management and allocation
    ... > As I'm writing a piece of code that basically acts as a server and ... > memory management is a topic that is quite crucial. ... Or can I just allocate the variable ... Nor is it usually necessary to set the pointer to ...
    (comp.lang.c)
  • Re: Virtual Machine implementation problem, Please help me to spot the bug
    ... I kept on getting error messages. ... You don't allocate enough memory here. ... Again conversions between pointer and integer types. ...
    (comp.lang.c)
  • Re: This is getting really weird.
    ... I thought 4 bytes for reference count and 4 for string length. ... > There should be no memory allocation for that line. ... > manager may allocate more space than requested for its own efficiency. ... > that New returned with a pointer to the string constant. ...
    (alt.comp.lang.borland-delphi)