swconfig: fix memory leak when cli call swlib_get_attr()
authornichel Chen <nichelnich@gmail.com>
Thu, 8 Jun 2023 00:04:56 +0000 (08:04 +0800)
committerChristian Marangi <ansuelsmth@gmail.com>
Sun, 11 Jun 2023 00:42:31 +0000 (02:42 +0200)
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>
package/network/config/swconfig/src/cli.c

index eab6c64742e96d1453c62b07d40b4824db6ed9fb..2601f346db1301e39b27152923e6bcacf0b50c28 100644 (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: