🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.lang.fortran
Article #460

Re: Structured Programming (was Re: “The end of software secrecy is almost upon us”)

#460
From: Lawrence D’Oliveiro
Date: Sun, 01 Nov 2026 23:38
142 lines
6736 bytes
Anyway, to get the discussion back on track:

I put together an example here
<https://gitlab.com/ldo/a_structured_discipline_of_programming>. This
is an extension module that offers services to Python code, because
that is just about the worst example I could think of, for those who
think gotos can cut it.

Problems I am trying to address:

  * Leaking memory: allocating something and forgetting to dispose of
    it
  * Double-free: the opposite problem, trying to free a memory block
    that has already been freed

The basic structured-programming pattern I follow is:

  1: Initialize a pointer variable to `NULL`
  2: Allocate memory for the pointer (this might fail)
  3: Correctly free the pointer memory, regardless of allocation
     success/failure

This project uses the implementation of a Python extension module as a
specific example, since Python itself is a highly dynamic language,
and so code that is written in a lower-level-language like C for
interfacing to Python typically has to deal a lot with allocation and
management of Python objects and other dynamic memory.

In more concrete terms, the code pattern looks like this:

    PyObject * obj = NULL; /* step 1 */
    do /*once*/
      {
        ... possible other stuff ...
        allocate obj; /* step 2 */
        if (PyErr_Occurred())
            break;
        ... possible other stuff using obj ...
      }
    while (false);
    Py_XDECREF(obj); /* step 3 */

Assuming there are no `goto`s in the “...” parts (or `return`
statements, or shenanigans like `setjmp`(3)/`longjmp`(3)), it should
be clear that, regardless of what happens in those parts (provided
they don’t free or reallocate `obj`), any memory allocated to `obj`
will be correctly freed.

Key to this pattern is the fact that `Py_XDECREF` is a noop (and
raises no error) if it is passed a `NULL` pointer. This is also the
semantics of the `free`(3) routine in the C standard library, and I
recommend that any memory-disposal routine you create implement the
same behaviour. It saves checking for unallocated storage in the
cleanup code: just unconditionally dispose of everything temporary
that might have been allocated.

The above basic structure scales easily. For example, coping with
multiple objects needing allocating:

    PyObject * obj1 = NULL;
    PyObject * obj2 = NULL;
    do /*once*/
      {
        ... possible other stuff ...
        allocate obj1;
        if (PyErr_Occurred())
            break;
        ... possible other stuff using obj1 ...
        allocate obj2;
        if (PyErr_Occurred())
            break;
        ... possible other stuff using obj1 and obj2 ...
      }
    while (false);
    Py_XDECREF(obj1);
    Py_XDECREF(obj2);

Nested blocks:

    PyObject * obj1 = NULL;
    do /*once*/
      {
        ... possible other stuff ...
        allocate obj1;
        if (PyErr_Occurred())
            break;
        ... possible other stuff using obj1 ...
          {
            PyObject * obj2 = NULL;
            do /*once*/
              {
                ... even more possible stuff using obj1 ...
                allocate obj2;
                if (PyErr_Occurred())
                    break;
                ... possible other stuff using obj1 and obj2 ...
              }
            while (false);
            Py_XDECREF(obj2);
          }
        if (PyErr_Occurred())
            break;
        ... yet more possible stuff using obj1 ...
      }
    while (false);
    Py_XDECREF(obj1);

Allocation within loops:

    for (ssize_t i = 0;;)
      {
        if (i == nr_items)
            break;
        PyObject * const item = PyTuple_GetItem(items, i);
        if (item == NULL)
            break;
          {
            PyObject * key = NULL;
            PyObject * value = NULL;
            do /*once*/
              {
                ... construct key ...
                if (PyErr_Occurred())
                    break;
                ... construct value ...
                if (PyErr_Occurred())
                    break;
                if (PyDict_SetItem(tempresult, key, value) < 0)
                    break;
              }
            while (false);
            Py_XDECREF(key);
            Py_XDECREF(value);
          }
        if (PyErr_Occurred())
            break;
        ++i;
      } /*for*/
    if (PyErr_Occurred())
        break;

Etc, etc.
Technical Details
Message-ID: <11c8ihn$2dr35$2@dont-email.me>
Path: mbox-mo1.pugleaf.net!archive.usenet.blueworldhosting.com!usenet.blueworldhosting.com!diablo1.usenet.blueworldhosting.com!eternal-september.org!feeder.eternal-september.org!nntp.eternal-september.org!.POSTED!not-for-mail
References: <11amvre$15far$1@dont-email.me> <11b5tdb$2cs5l$1@dont-email.me> <11b64cp$end$1@panix2.panix.com> <11b64hj$2faos$1@dont-email.me> <11b679m$6dl$1@panix2.panix.com> <11b6vc4$2npqv$1@dont-email.me> <11b87jg$37b7t$1@dont-email.me> <11b884b$p2o9$1@dont-email.me> <11b94he$3hdo3$2@dont-email.me> <11b9qd6$pq4i$1@dont-email.me> <11b9r5r$3nppf$1@dont-email.me> <11baekk$3v7n1$1@dont-email.me> <11bbl4f$du80$2@dont-email.me> <11bbo58$ek3q$1@dont-email.me> <11bbqns$fe31$1@dont-email.me> <11bbron$fmi2$1@dont-email.me> <11bc09b$gsv1$1@dont-email.me> <11bd6ed$ttau$1@dont-email.me> <11bejnh$1eab6$1@dont-email.me> <11berc9$1ge43$1@dont-email.me> <11bm2kg$2d3a$1@dont-email.me> <11bm7mf$3thd$1@dont-email.me> <11bmctb$5l5h$1@dont-email.me> <11bmi1p$78mo$1@dont-email.me> <11bod1u$ugib$2@dont-email.me> <11bohmi$10aqu$2@dont-email.me> <11bqe9q$1k0hc$1@dont-email.me> <11br86k$1uehc$2@dont-email.me> <11brjgd$21rhi$1@dont-email.me> <11brk0r$21r0v$2@dont-email.me>

Show Full Headers
Complete Article Headers
Path: mbox-mo1.pugleaf.net!archive.usenet.blueworldhosting.com!usenet.blueworldhosting.com!diablo1.usenet.blueworldhosting.com!eternal-september.org!feeder.eternal-september.org!nntp.eternal-september.org!.POSTED!not-for-mail
From: Lawrence D’Oliveiro <ldo@nz.invalid>
Newsgroups: comp.lang.fortran,comp.lang.c++,alt.comp.lang.rust,alt.folklore.computers
Subject: Re: Structured Programming (was Re: “The end of
 software secrecy is almost upon us”)
Date: Sun, 1 Nov 2026 23:38:32 -0000 (UTC)
Organization: A noiseless patient Spider
Lines: 142
Message-ID: <11c8ihn$2dr35$2@dont-email.me>
References: <11amvre$15far$1@dont-email.me> <11b5tdb$2cs5l$1@dont-email.me>
	<11b64cp$end$1@panix2.panix.com> <11b64hj$2faos$1@dont-email.me>
	<11b679m$6dl$1@panix2.panix.com> <11b6vc4$2npqv$1@dont-email.me>
	<11b87jg$37b7t$1@dont-email.me> <11b884b$p2o9$1@dont-email.me>
	<11b94he$3hdo3$2@dont-email.me> <11b9qd6$pq4i$1@dont-email.me>
	<11b9r5r$3nppf$1@dont-email.me> <11baekk$3v7n1$1@dont-email.me>
	<11bbl4f$du80$2@dont-email.me> <11bbo58$ek3q$1@dont-email.me>
	<11bbqns$fe31$1@dont-email.me> <11bbron$fmi2$1@dont-email.me>
	<11bc09b$gsv1$1@dont-email.me> <11bd6ed$ttau$1@dont-email.me>
	<11bejnh$1eab6$1@dont-email.me> <11berc9$1ge43$1@dont-email.me>
	<11bm2kg$2d3a$1@dont-email.me> <11bm7mf$3thd$1@dont-email.me>
	<11bmctb$5l5h$1@dont-email.me> <11bmi1p$78mo$1@dont-email.me>
	<11bod1u$ugib$2@dont-email.me> <11bohmi$10aqu$2@dont-email.me>
	<11bqe9q$1k0hc$1@dont-email.me> <11br86k$1uehc$2@dont-email.me>
	<11brjgd$21rhi$1@dont-email.me> <11brk0r$21r0v$2@dont-email.me>
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Injection-Date: Sun, 01 Nov 2026 23:38:32 +0000 (UTC)
Injection-Info: dont-email.me;
	logging-data="2550885"; mail-complaints-to="abuse@eternal-september.org";	posting-account="U2FsdGVkX1/kUjM7A6KHZIbidSFWBPa/"; posting-host="e3160788d8ee1ce0c3252f1aed4b293c"
User-Agent: Pan/0.165 (Kostiantynivka)
Cancel-Lock: sha1:qgYOcsE93kPLh9htB1VERqPcZ5I= sha256:Bn9VTdR9A3/PBVFStGem3MIgef7Ey8UeQWl637b1jNE=
	sha1:6skii9Hwqnn4IGFif0RzBPE5h30= sha256:sB2omqVI2MDhmSv/Joaq5kLUTG89lngzuYarP79Wx14=