[Dnsmasq-discuss] [PATCH] Remove NULL check for intname.

Kevin Lyda kevin at ie.suberic.net
Thu Oct 5 23:14:22 BST 2017


That's not actually correct in practice.  If you'd like to see that I'm
correct take the following two programs:

foo.c:
#include <string.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
  if (strlen(argv[0]) == 0) {
    printf("Command empty");
  } else {
    printf("Command not empty");
  }
}
bar.c:
#include <string.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
  if (*argv[0] == '\0') {
    printf("Command empty");
  } else {
    printf("Command not empty");
  }
}

Next compile them to assembly like so:

for f in {foo,bar}.c; do gcc -O2 -S $f; done

And then compare them:

diff {foo,bar}.s

They should be the same (possibly different by a ".file" line). And if you
inspect the resulting code, there won't be a call to strlen or to any
function at all (well, except printf).

The reason is that gcc, like most C compilers since the 90s, optimises a
number of common functions in the standard C library. Which means that
developers can stick with writing code that will be well-optimised *and*
highly readable.

Kevin



On Thu, Oct 5, 2017 at 8:31 PM Roy Marples <roy at marples.name> wrote:

> On 05/10/2017 03:23, Rosen Penev wrote:
> > @@ -1239,7 +1238,7 @@ static struct serverfd *allocate_sfd(union
> mysockaddr *addr, char *intname)
> >   #endif
> >       }
> >
> > -  if (intname && strlen(intname) != 0)
> > +  if (!strlen(intname))
> >       ifindex = if_nametoindex(intname); /* index == 0 when not binding
> to an interface */
> >
> >     /* may have a suitable one already */
> >
>
> I have no comment on the functionality of the patch (it if intname needs
> to be NULL checked or not), but this is not a good use of strlen.
>
> This could be re-written as
>
> if (*intname != '\0')
>
> Which saves a function call because the actual length of the string is
> not used.
>
> Roy
>
> _______________________________________________
> Dnsmasq-discuss mailing list
> Dnsmasq-discuss at lists.thekelleys.org.uk
> http://lists.thekelleys.org.uk/mailman/listinfo/dnsmasq-discuss
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.thekelleys.org.uk/pipermail/dnsmasq-discuss/attachments/20171005/832552e2/attachment.html>


More information about the Dnsmasq-discuss mailing list