Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: [PATCH] fix several memory leaks



> 2018/07/29 3:57, Bart Schaefer <schaefer@xxxxxxxxxxxxxxxx> wrote:
> 
> On Sat, Jul 28, 2018, 11:06 AM Jun T. <takimoto-j@xxxxxxxxxxxxxxxxx> wrote:
> 
>> 
>> Parameters
>> are supposed to be freed by setfeatureenables(,,NULL),
>> and explicitly freeing them in cleanup_() is not a good
>> example.
>> 
> 
> Side-effect of this module having been created before the features
> mechanism existed, and incompletely updated after.

If we want to show that each feature can be independently enabled, then
setting the parameter exarr (arrparam) etc. in bin_example() is better
avoided.

But we still need to make sure that the parameters are allocated only
if they are enabled. We can do this, for example, as in the patch below,
but is this a "good example"?



diff --git a/Src/Modules/example.c b/Src/Modules/example.c
index c80c9e7b2..b10c2f0e5 100644
--- a/Src/Modules/example.c
+++ b/Src/Modules/example.c
@@ -42,15 +42,14 @@ static int
 bin_example(char *nam, char **args, Options ops, UNUSED(int func))
 {
     unsigned char c;
-    char **oargs = args, **p = arrparam;
-    long i = 0;
+    char **p = arrparam;
 
     printf("Options: ");
     for (c = 32; ++c < 128;)
 	if (OPT_ISSET(ops,c))
 	    putchar(c);
     printf("\nArguments:");
-    for (; *args; i++, args++) {
+    for (; *args; args++) {
 	putchar(' ');
 	fputs(*args, stdout);
     }
@@ -66,12 +65,6 @@ bin_example(char *nam, char **args, Options ops, UNUSED(int func))
 	while (*p) printf(" %s", *p++);
     printf("\n");
 
-    intparam = i;
-    zsfree(strparam);
-    strparam = ztrdup(*oargs ? *oargs : "");
-    if (arrparam)
-	freearray(arrparam);
-    arrparam = zarrdup(oargs);
     return 0;
 }
 
@@ -221,12 +214,19 @@ enables_(Module m, int **enables)
 int
 boot_(Module m)
 {
-    intparam = 42;
-    strparam = ztrdup("example");
-    arrparam = (char **) zalloc(3 * sizeof(char *));
-    arrparam[0] = ztrdup("example");
-    arrparam[1] = ztrdup("array");
-    arrparam[2] = NULL;
+    int *enables = getfeatureenables(m, &module_features);
+
+    if (enables[5]) {
+	arrparam = (char **) zalloc(3 * sizeof(char *));
+	arrparam[0] = ztrdup("example");
+	arrparam[1] = ztrdup("array");
+	arrparam[2] = NULL;
+    }
+    if (enables[6])
+	intparam = 42;
+    if (enables[7])
+	strparam = ztrdup("example");
+
     return addwrapper(m, wrapper);
 }
 




Messages sorted by: Reverse Date, Date, Thread, Author