开发者

what is the initial value of a pointer in c file

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?


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.


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.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜