Reputation: 1779
Main:
char *tmpip;
tmpip = get_public_ip();
function get_public_ip:
char * get_public_ip(void){
char *ipresult;
if(((ipresult = malloc(17))) == NULL){
perror("malloc on pub ip");
exit(1);
}
if(fgets(ipresult, 16, tmpfp) == NULL){
perror("fgets error pubip");
exit(1);
}
fclose(tmpfp);
return ipresult;
}
My question is:
it is good to do inside the main free(tmpip)
or it is wrong?
Upvotes: 2
Views: 2043
Reputation: 279225
If dynamic allocation is used, then freeing the pointer with free(tmpip)
is definitely good! The function get_public_ip
just needs to document that to release resources the caller must ensure free
is called on the return value.
An alternative would be to provide a function void free_public_ip(char*buf) {free(buf);}
, and document that to release resources the caller must use that. This gives you some flexibility in future to change how the memory is allocated, without calling code changing. It's certainly not necessary.
In my opinion it doesn't really make sense to malloc
a small fixed-size buffer like that. The header file for get_public_ip
could #define PUBLIC_IP_SIZE (17)
and take a char*
parameter, then the caller could do:
char tmpip[PUBLIC_IP_SIZE];
get_public_ip(tmpip);
// no more thinking required
Instead of:
char *tmpip = get_public_ip();
// code here, perhaps does more things that could fail,
// maybe some thinking required to ensure every code path passes through:
free(tmpip);
If that number 17
can change in future without the opportunity to re-compile the calling code (for instance if this is a library and you require binary compatibility), then dynamic allocation would be justified.
Upvotes: 1
Reputation: 33511
It's a good way of coding: you malloc()
some memory in a function and free()
it when not needed anymore. Be sure to comment your function or prototype that it will malloc()
the memory needed, so you know that you have to free()
it.
Upvotes: 4
Reputation:
Why would it be wrong? You don't really have any other option to free the allocated buffer somewhere else... It's idiomatic in C to call a function that allocates memory, then make the caller (outer) function resposible for freeing that memory.
Upvotes: 1