views:

173

answers:

2

In following code, is it possible cause some memory leaks?

reference-ril.c
static void requestRadioPower(void *data, size_t datalen, RIL_Token t)
{
    ....
    ATResponse *p_response = NULL;
    ....
    err = at_send_command(cmd, &p_response);   // it's a memory leakage or not ?
    ....
    at_response_free(p_response);
    ....
}

And in other function:

static void requestOrSendPDPContextList(RIL_Token *t)
{
    ATResponse *p_response;
    ....
    err = at_send_command_multiline ("AT+CGACT?", "+CGACT:", &p_response);  
    // it's a leakage or not ?
    ....
    at_response_free(p_response);
    ....
}

Actually, these function will returned before calling at_response_free(p_response) in some cases. I suppose we shout set ATResponse *p_response to NULL first, right ? Set pointer to NULL is a good idea or not?

+1  A: 

Setting the pointer to null is certainly a good idea; but neither case is a memory leak.

The initial value of a pointer in C is garbage, as is the initial value of any variable that isn't initialized. (This is because of efficiency, or so I'm told, and needs to be kept in mind.)

Williham Totland
+3  A: 

It depends:

  • if at_send_command_multiline and at_send_command look at the value pointed-to by their respective last arguments (&p_response), then you should set them to predictable values. This may mean that you set p_response to NULL. If the functions allocate memory for the pointer without looking at the initial value, then you are okay. To answer your particular question, a variable declared in a function, unless declared static, has no default value.
  • if the at_send_command* functions always allocate memory for the last argument, then you must free the memory. If they allocate only in the case of success, then you must free only in the case of success. A simple rule is that for every malloc() or calloc(), there should be a free(). (realloc() changes this a bit, but you shouldn't need to worry about it right now).

In other words, you need to look at the documentation of at_send_command* functions, or look in the definition of the functions to answer your questions fully.

Alok
@Alok - "To answer your particular question, a variable declared in a function, unless declared static, has no default value." to be a little more clear here, not only is there no default value, it could be any value. As it is not declared static it is created on the stack and not automatically initialized, and therefor can have any value that may have been left around on the stack.
simon
@simon: you are right, although I avoid the use of the word "stack" for automatically initialized variables: there may or may not be a stack as far as the C standard is concerned.
Alok