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
andat_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 setp_response
toNULL
. 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 declaredstatic
, 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 everymalloc()
orcalloc()
, there should be afree()
. (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.)
精彩评论