Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove unnecessary null pointer checks #417

Closed
elfring opened this issue Jan 11, 2025 · 3 comments
Closed

Remove unnecessary null pointer checks #417

elfring opened this issue Jan 11, 2025 · 3 comments

Comments

@elfring
Copy link

elfring commented Jan 11, 2025

An extra null pointer check is not needed in functions like the following.

@thom311
Copy link
Owner

thom311 commented Jan 12, 2025

We don't need an issue for this. It's mostly a cosmetic change anyway.

If you care enough, please open a pull request that changes such things. Patch welcome.


Where possible, I think it's better to avoid explicit free and use __attribute__((cleanup)) instead. For excample, instead of explicit free , it would be better to do:

diff --git i/src/lib/cls.c w/src/lib/cls.c
index 9c94b0de7f67..fe5574ffc5d1 100644
--- i/src/lib/cls.c
+++ w/src/lib/cls.c
@@ -50,16 +50,13 @@ void nl_cli_cls_parse_proto(struct rtnl_cls *cls, char *arg)
 
 struct rtnl_ematch_tree *nl_cli_cls_parse_ematch(struct rtnl_cls *cls, char *arg)
 {
+        _nl_auto_free char *errstr = NULL;
         struct rtnl_ematch_tree *tree;
-        char *errstr = NULL;
         int err;
 
         if ((err = rtnl_ematch_parse_expr(arg, &errstr, &tree)) < 0)
                  nl_cli_fatal(err, "Unable to parse ematch expression: %s",
                                      errstr);
-        
-        if (errstr)
-                 free(errstr);
 
         return tree;
 }

the benefit is that in this case the auto variable on the stack is indicated to "own" the resource it points to.

@thom311 thom311 closed this as completed Jan 12, 2025
@elfring
Copy link
Author

elfring commented Jan 12, 2025

💭 I am curious if another software developer (besides me) can get into the mood to apply a corresponding update suggestion which could be generated by the software “Coccinelle” (also with the help of a variant from the following script).

@Remove_unnecessary_pointer_checks@
expression x;
@@
-if (\(x != 0 \| x != NULL\))
    free(x);

@elfring
Copy link
Author

elfring commented Jan 12, 2025

How do you think about to improve the API documentation also for a function like nlmsg_free() (which tolerates the passing of null pointers)? 🤔

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants