Fix memory leak when realloc fails

This commit is contained in:
Chocobo1 2016-01-04 11:51:49 +08:00
parent e076899a37
commit 948b883966
2 changed files with 13 additions and 9 deletions

View File

@ -723,7 +723,7 @@ unsigned short *
get_portmappings_in_range(unsigned short startport, unsigned short endport, get_portmappings_in_range(unsigned short startport, unsigned short endport,
int proto, unsigned int * number) int proto, unsigned int * number)
{ {
unsigned short * array; unsigned short *array, *array2;
unsigned int capacity; unsigned int capacity;
unsigned short eport; unsigned short eport;
ipfgeniter_t iter; ipfgeniter_t iter;
@ -781,13 +781,15 @@ get_portmappings_in_range(unsigned short startport, unsigned short endport,
{ {
/* need to increase the capacity of the array */ /* need to increase the capacity of the array */
capacity += 128; capacity += 128;
array = realloc(array, sizeof(unsigned short)*capacity); array2 = realloc(array, sizeof(unsigned short)*capacity);
if(!array) if(!array2)
{ {
syslog(LOG_ERR, "get_portmappings_in_range() : realloc(%lu) error", sizeof(unsigned short)*capacity); syslog(LOG_ERR, "get_portmappings_in_range() : realloc(%lu) error", sizeof(unsigned short)*capacity);
*number = 0; *number = 0;
free(array);
return NULL; return NULL;
} }
array = array2;
} }
array[*number] = eport; array[*number] = eport;
(*number)++; (*number)++;

View File

@ -430,7 +430,7 @@ get_portmappings_in_range(unsigned short startport,
int proto, int proto,
unsigned int * number) unsigned int * number)
{ {
unsigned short * array = NULL; unsigned short *array = NULL, *array2 = NULL;
unsigned int capacity = 128; unsigned int capacity = 128;
int i, count_rules, total_rules = 0; int i, count_rules, total_rules = 0;
struct ip_fw * rules = NULL; struct ip_fw * rules = NULL;
@ -459,12 +459,14 @@ get_portmappings_in_range(unsigned short startport,
&& eport <= endport) { && eport <= endport) {
if(*number >= capacity) { if(*number >= capacity) {
capacity += 128; capacity += 128;
array = realloc(array, sizeof(unsigned short)*capacity); array2 = realloc(array, sizeof(unsigned short)*capacity);
if(!array) { if(!array2) {
syslog(LOG_ERR, "get_portmappings_in_range() : realloc(%lu) error", sizeof(unsigned short)*capacity); syslog(LOG_ERR, "get_portmappings_in_range() : realloc(%lu) error", sizeof(unsigned short)*capacity);
*number = 0; *number = 0;
free(array);
goto error; goto error;
} }
array = array2;
} }
array[*number] = eport; array[*number] = eport;
(*number)++; (*number)++;