RSS / Atom

I should know that, C edition

2016-03-26 , , , Comment

I had drinks with friends a couple of weeks ago and I mentioned a Hacker News discussion that included a link to a thread involving Rajiv Kurian in a comment on undefined behavior1 in C (the thread isn’t itself all that interesting but Krister Walfridsson blog post on compiler optimization is). They’re more experienced and/or better with C than I am and we sipped our beers and laughed at my and at our mutual expense for not knowing some of these. I don’t write much C for work in the past several years but I do make a point to re-educate myself.

Today I was reading Bruce Dawson’s blog and one of the bug reports he filed for Chromium against the Microsoft VC++ compiler included an array initializer construct I hadn’t seen (to some relief that I’m not a complete twit, he hadn’t either). I can’t be the only one who learned C before C99 (or before C90…) and didn’t know this syntax exists, from the GCC manual:

6.27 Designated Initializers

In ISO C99 you can give the elements in any order, specifying the array indices or structure field names they apply to, and GNU C allows this as an extension in C90 mode as well. This extension is not implemented in GNU C++.

To specify an array index, write ‘[index] =’ before the element value. For example,

    int a[6] = { [4] = 29, [2] = 15 };

is equivalent to

    int a[6] = { 0, 0, 15, 0, 29, 0 };

The index values must be constant expressions, even if the array being initialized is automatic.

and note that:

If the value in it has side-effects, the side-effects happen only once, not for each initialized field by the range initializer.

Have a sip and laugh, but I know it now.

1 re-read What Every C Programmer Should Know About Undefined Behavior #1/3



2016-03-10 , , , Comment

I often find myself needing to parse a file for bits of text and piping that through to other commands but while the file has a reasonably good syntax, the structure or ordering doesn’t lend itself to just using awk. I used to reach for Perl or Ruby and bang out a one-off parser but for the past few years if I find myself writing more than a one-liner I switch to Kaz Kylheku’s TXR. It’s taking me time to grasp, mostly because I only work with it on the harder problems, but it works well.

Today I needed to fiddle with the VM’s on my workstation and couldn’t remember their IP’s. I regularly create and delete these and the IP addresses shuffle around. VMWare uses ISC DHCP as its dhcp server and I’m quite familiar with the lease file which has a series of lease declarations each with a curly-brace block containing a number of statements describing the configuration which can appear in any order. I’m only interested in a few.

Here’s a quickie script to extract what I needed:

#!/usr/bin/env txr -f
lease @{IPADDR /\d+\.\d+\.\d+\.\d+/} {@\

@/\s/client-hostname "@HOSTNAME";
@/\s/hardware ethernet @{MAC /([a-fA-F0-9][a-fA-F0-9][:\-])*([a-fA-F0-9][a-fA-F0-9])/};

Here’s the output on my workstation, which is simple to filter through other tools:

$ dhcp-leases /var/db/vmware/vmnet-dhcpd-vmnet8.leases,ubuntu,00:0c:29:96:6b:86,ross-a0cfd9724f,00:0c:29:47:ce:9a,pfSense,00:0c:29:65:5b:59,ubuntu,00:0c:29:6d:d6:b2,fbsd,00:0c:29:81:76:d6,archvm1,00:0c:29:e1:3c:3e,obsd,00:0c:29:7b:44:b3,vm1ubuntu,00:0c:29:bc:9f:39,vmdeb1,00:0c:29:34:4a:57,box,00:0c:29:1e:e8:b1,Knoppix,00:0c:29:f9:53:2b,win2kvm01,00:0c:29:8e:dd:41

Perfect! Including the shebang line at the top it’s 397 bytes.


Dev Tools & Tricks round-up 2014

2014-12-28 , , , Comment

A quick list of my favorite development tools and tricks, in no particular order:

  • Emacs! Okay, I do use Eclipse sometimes but nearly all my editing is done in Emacs. I’m waiting (maybe alone…) for Guile-Emacs to get to a release sometime before the ubiquity of the flying car and Mr. Fusion so I don’t have to worry about completely buggering up my editor with a poorly thought out background task.
  • The D-Language. I don’t want to write (or read) C++ unless I’m forced but D fits my programming niche.
  • When there isn’t eldoc, there’s Dash. Very convenient pop-up API documentation.
  • Cint, an interpreter for pre-C99 ANSI C and ISO C++ 2003, and its successor Cling, based on LLVM. Invaluable for interactively exploring vendor libraries or testing bits of code.
  • OSX FUSE. The file system in user space (FUSE) driver. I use it with SSHFS to present remote and VM filesystems as local ones for development without the hassle of syncing or using Emac’s Tramp mode.
  • Pry A better Ruby REPL (run, eval, print loop) than the included IRB. I wish I had known about this years ago. Thanks to Shahriar for pointing me to this and Zack for showing me why it’s better.
  • ZMODEM. It’s like a 1987 flashback but ZMODEM is the most convenient way to copy files to and from a host where you have SSH access. I have mine triggered in Iterm2.


Chibios/RT docset for

2014-12-05 , , , Comment

The is a great little offline API/documentation browser (there’s also zeal, which compiles on Unix/Linux and Windows). It’s fairly easy to produce your own docset so I put together one for ChibiOS/RT version 2.2.6, the open source RTOS I’m working with. Download (11MB) org.chibios.tgz from Google Drive.


D Language

2014-04-19 , , ,

I recently had to write a moderate amount of C around vendor libraries and get things working in three days. The effort resulted in about 3200 lines of ugly, hastily written code that compiled under gcc and clang with -Wall -Werror -pedantic and looked reasonably leak-free in Valgrind. I whittled it down over the following week as time permitted to a bit over 2000 lines.

Lines of code is a lousy metric, but it’s easy to extract using available tools. Here are the counts from cloc for the original two projects in C:

Language                     files          blank        comment           code
C                                3            298            193           1869
C/C++ Header                     3             32              0            178
SUM:                             6            330            193           2047

Quick passes with grep counts 11, 13, and 16 functions.

A better metric might be complexity. Running it through the cyclomatic complexity checker cyclo results in scores of 79, 99, and 110. These seem completely off the charts (10-15 is the recommended range for a “module”). Quick runs against some code I had lying around shows that these numbers are high (OpenBSD’s strncpy and a naive CRC-16 implementation I had both score a 5, SolarDesigner’s concat function scores a 12) but we can use them for comparison. Let’s torture the numbers by averaging, 13.3 functions and a score of 96, for about 7.2 complexity per function.

I’m always on the look out for an advantage (I need them…) and saw a recent announcement of a release of the D Language compiler. The features piqued my interest: native compilation, garbage collection and dynamic memory, types, classes, interfaces, mixins, exceptions, extensive standard library, and an easy interface to C. Walter Bright, the language designer and writer of the reference compiler, is well known. There’s a decent website, a tutorial, and C++ guru Andrei Alexandrescu wrote the book on the language. Cool, I thought, a better C++. I bought the book, started coding familiar tasks, and dug in during my little free time.

It went easily and I had a satisfactory result in a few days. The equivalent in D:

Language          files     blank   comment      code    scale   3rd gen. equiv
D                     2       109        96       709 x   1.70 =        1205.30
SUM:                  2       109        96       709 x   1.70 =        1205.30

Notice that I’ve reduced the number of files, I’ll get to that. The pass through grep counts 8 and 13 functions, of which 3 of them in each source file are two-line logging routines to replace the classic C preprocessor macros dbgprintf and errprintf. cyclo doesn’t perfectly handle D, but it’s reasonably close in syntax to C/C++, producing scores of 45 and 61. Twisting numbers again gives 10.5 and 53 for a score of about 5 per function. The improvement in complexity is on par with the reduction in lines of code.

The kicker is that not only are the D versions are shorter and easier to comprehend, they do more and have more robust error-checking and exception-handling. Overall I’m more confident they behave correctly. I replaced two independent programs with a single one. I replaced a throttled fork()-ing server with a fixed pool of workers. I leveraged associative arrays, JSON, and Base64 without rolling my own or borrowing from other Open Source libraries. None of this is stuff I couldn’t implement or find somewhere but I didn’t have to. Classic force multiplier of a programming language.


Burst Battery

2013-05-19 , , , Comment

The spare Macbook Pro battery burst overnight. It was sitting on my desk fully charged.

I’m glad it wasn’t in the laptop.


« Older Posts