swconfig: fix memory leak when cli call swlib_get_attr()

The cli is a one-time run, and memory leaks would have been irrelevant. But people call libsw with cli programs as samples.
Doing a good job of memory management calls means that people who call libsw are not so easy to make mistakes.

Signed-off-by: nichel Chen <nichelnich@gmail.com>
This commit is contained in:
nichel Chen 2023-06-08 08:04:56 +08:00 committed by Christian Marangi
parent 79844637df
commit 2b0b28f479
No known key found for this signature in database
GPG Key ID: AC001D09ADBFEAD7
1 changed files with 22 additions and 1 deletions

View File

@ -101,6 +101,24 @@ speed_str(int speed)
return "unknown";
}
static void
free_attr_val(const struct switch_attr *attr, const struct switch_val *val)
{
switch (attr->type) {
case SWITCH_TYPE_STRING:
free(val->value.s);
break;
case SWITCH_TYPE_PORTS:
free(val->value.ports);
break;
case SWITCH_TYPE_LINK:
free(val->value.link);
break;
default:
break;
}
}
static void
print_attr_val(const struct switch_attr *attr, const struct switch_val *val)
{
@ -150,8 +168,10 @@ show_attrs(struct switch_dev *dev, struct switch_attr *attr, struct switch_val *
printf("\t%s: ", attr->name);
if (swlib_get_attr(dev, attr, val) < 0)
printf("???");
else
else {
print_attr_val(attr, val);
free_attr_val(attr, val);
}
putchar('\n');
}
attr = attr->next;
@ -354,6 +374,7 @@ int main(int argc, char **argv)
goto out;
}
print_attr_val(a, &val);
free_attr_val(a, &val);
putchar('\n');
break;
case CMD_LOAD: