Code Critique Request

Status
Not open for further replies.
Hi everyone - having been burned by GPFs in the past, I've decided for my next project to hide all memory accesses behind a layer of abstraction. I've written some code to do this (and a couple of functions using that code). Though I haven't compiled it yet (next step will be to write a small program which does MTF to a file, then a program which does the reverse), I'm pretty sure my code works.

I was wondering if anyone would like to take a look at it and point out obvious omissions or the like; for example, I was performing mcell_check at the start of every function before I realized the only functions which need that are the ones which have to directly access the buffer. I haven't implemented some memory comparison functions (or a port of memcpy, etc) yet, but I plan to.

Style comments and the like are also welcome.

Here are the four files I have now (the code is distributed under the GPL):
[The language used is fully portable ANSI C under the 1999 standard; the only assumption I make is that bytes are 8-bit, so sue me :D ]
code:<HR>
Code:
/* mcell.c - Memory Cell Abstraction Interface */
/* GPLed - Stephan T. Lavavej - [url=http://stl.caltech.edu]http://stl.caltech.edu[/url] */<P>#include "mcell.h"<P>/* Allocates a memory cell; printf()s and exit()s if impossible */
/* Memory is initialized to 0 */
struct mcell mcell_alloc(const char *name, size_t len) {
    struct mcell returnstruct;<P>    returnstruct.name = name;
    returnstruct.length = len;
    returnstruct.buf = malloc(len);<P>    if (returnstruct.buf == NULL) {
        printf("ERROR: Cannot malloc %zd bytes named %s\n", len, name);
        exit(EXIT_FAILURE);
    }<P>    mcell_zero(returnstruct);<P>    return returnstruct;
}<P>/* Returns the size of a memory cell */
size_t mcell_size(struct mcell in) {
    return in.length;
}<P>/* Returns the name of a memory cell */
const char * mcell_name(struct mcell in) {
    return in.name;
}<P>/* Is a location n in a memory cell inaccessible? */
int mcell_oob(struct mcell in, size_t n) {
    return ((n < 0) || (n >= mcell_size(in)));
}<P>/* Returns the nth byte in a memory cell */
/* printf()s and exit()s if out-of-bound access is attempted */
unsigned char mcell_get(struct mcell in, size_t n) {
    mcell_check(in);
    if (mcell_oob(in, n)) {
        printf("ERROR: Attempt to access byte %zd from cell %s\n",
            n, mcell_name(in));
        exit(EXIT_FAILURE);
    }
    return in.buf[n];
}<P>/* Place a byte uc into a memory cell at position n */
/* printf()s and exit()s if out-of-bound access is attempted */
void mcell_put(unsigned char uc, struct mcell in, size_t n) {
    mcell_check(in);
    if (mcell_oob(in, n)) {
        printf("ERROR: Attempt to put %d in byte %zd of cell %s\n",
            uc, n, mcell_name(in));
        exit(EXIT_FAILURE);
    }
    in.buf[n] = uc;
}<P>/* Zero out a memory cell */
void mcell_zero(struct mcell in) {
    mcell_fill(in, 0);
}<P>/* Fill memory cell with byte uc */
void mcell_fill(struct mcell in, unsigned char uc) {
    mcell_check(in);
    memset(in.buf, uc, mcell_size(in));
}<P>/* Do nothing if mcell active */
/* printf() and exit() if mcell freed */
/* RULE: mcell_check only when directly accessing mcell's memory */
void mcell_check(struct mcell in) {
    if (in.buf == NULL) {
        printf("ERROR: Cell %s already freed.\n", mcell_name(in));
        exit(EXIT_FAILURE);
    }
}<P>/* Free a memory cell's buffer and null out its pointer */
/* Name and size are not modified */
void mcell_free(struct mcell *pcell) {
    mcell_check(*pcell); /* Cannot free a freed memory cell */
    free(pcell->buf);
    pcell->buf = NULL;
}<P>/* Returns the nth byte in a memory cell, treating it as circular */
/* Negative n causes printf() then exit() */
unsigned char mcell_circleget(struct mcell in, size_t n) {
    mcell_check(in);<P>    if (n < 0) {
        printf("ERROR: Attempt to circleget %zd byte from %s, length %zd\n",
            n, mcell_name(in), mcell_size(in));
        exit(EXIT_FAILURE);
    }<P>    return in.buf[n % mcell_size(in)];
}
code:<HR>
Code:
/* mcell.h - Memory Cell Abstraction Interface */
/* GPLed - Stephan T. Lavavej - [url=http://stl.caltech.edu]http://stl.caltech.edu[/url] */<P>#ifndef MCELL_H
#define MCELL_H<P>#include <stdio.h>
#include <stdlib.h><P>/* The basic unit of storage */
struct mcell {
    const char *    name;   /* A pointer to a string constant */
    size_t          length; /* How many bytes are being stored */
    unsigned char * buf;    /* The memory buffer itself */
};<P>/* Prototypes */
struct mcell    mcell_alloc(const char *name, size_t len);
void            mcell_free(struct mcell *pcell);
void            mcell_check(struct mcell in);
int             mcell_oob(struct mcell in, size_t n);
size_t          mcell_size(struct mcell in);
const char *    mcell_name(struct mcell in);<P>unsigned char   mcell_get(struct mcell in, size_t n);
void            mcell_put(unsigned char uc, struct mcell in, size_t n);
unsigned char   mcell_circleget(struct mcell in, size_t n);<P>void            mcell_zero(struct mcell in);
void            mcell_fill(struct mcell in, unsigned char uc);<P>#endif /* End of: #ifndef MCELL_H */
code:<HR>
Code:
/* mtf.c - Move-To-Front Functions */
/* GPLed - Stephan T. Lavavej - [url=http://stl.caltech.edu]http://stl.caltech.edu[/url] */<P>#include "mtf.h"<P>/* Perform a Move-To-Front transformation on a memory cell */
void mcell_mtf(struct mcell in) {
    size_t st;
    int n;
    unsigned char uc, out, list[256];<P>    /* Initialize MTF list */
    for (n = 0; n < 256; n++) {
        list[n] = n;
    }<P>    for (st = 0; st < mcell_size(in); st++) {
        uc = mcell_get(in, st);             /* Input character */
        out = memchr(list, uc, 256) - list; /* Where is it in the list? */
        mcell_put(out, in, st);             /* Write that back */
        if (out != 0) {                     /* If char read isn't 1st */
            memmove(list + 1, list, out);   /* Move characters down */
            list[0] = uc;                   /* Put read character 1st */
        }
    }
}<P>/* Reverse a Move-To-Front transformation on a memory cell */
void mcell_unmtf(struct mcell in) {
    size_t st;
    int n;
    unsigned char uc, out, list[256];<P>    /* Initialize MTF list */
    for (n = 0; n < 256; n++) {
        list[n] = n;
    }<P>    for (st = 0; st < mcell_size(in); st++) {
        uc = mcell_get(in, st);             /* Input character */
        out = list[uc];                     /* Decoded character */
        mcell_put(out, in, st);             /* Write decoded character */
        if (uc != 0) {                      /* If value written wasn't 1st */
            memmove(list + 1, list, uc);    /* Move characters down */
            list[0] = out;                  /* Put read character 1st */
        }
    }
}
code:<HR>
Code:
/* mtf.h - Move-To-Front Functions */
/* GPLed - Stephan T. Lavavej - [url=http://stl.caltech.edu]http://stl.caltech.edu[/url] */<P>#ifndef MTF_H
#define MTF_H<P>#include <stdlib.h>
#include "mcell.h"<P>/* Prototypes */
void mcell_mtf(struct mcell in);
void mcell_unmtf(struct mcell in);<P>#endif /* End of: #ifndef MTF_H */

Thanks to anyone who'd like to donate their time.
--
Stephan T. Lavavej

[This message was edited by Stephan T. Lavavej on December 24, 2001 at 21:57.]
 

angst

Smack-Fu Master, in training
51
A few comments, nothing major, just a handful of observations...

1.
code:<HR>
Code:
returnstruct.name = name;

you assume that the name's scope supersets this mcell's lifetime. If that is indeed always the case ( name is static/global/etc ) than feel free to skip over this section, however if anyone is planning to do anything remotely resemling the following two snippets of code, then you probably need to copy it out.

code:<HR>
Code:
struct mcell foo( ) {
char name[] = "angst";
return mcell_alloc(name, 128); /* foo's stack pointer is crushed, so is "angst", any subsequent access to name in this mcell's struct will result in an undetermined stack error */
}

code:<HR>
Code:
struct mcell foo( ) {
char* name = strdup("angst"); /* little redundant, but hey it's a stupid example */
struct mcell mc = mcell_alloc(name, 128); /* still ok */
free(name); /* doh, from now on any name access will result in an FMR */
return mc;
}

2.
code:<HR>
Code:
struct mcell mcell_alloc(const char *name, size_t len)

I noticed that in most functions mcell struct is being passed in by value or returned as a copy of a local instance ( mcell_alloc(...) ). Have you considered returning a pointer to a heap allocated structure from the allocation routine? As far as passing by value, I guess performace is not a big factor ( passing in a 4 byte pointer vs copying a 12 byte struct ), so this boils down to personal preference.

3.
code:<HR>
Code:
printf("ERROR:...

Using stderr for errors is actually not a bad idea, at least it lets me seperate true errors from other garbage my programs spit out to stdout. On the flipside, you terminate after every error, plus you mark them with keyword ( ERROR ), so there is no chance for confusion. Additionally, I usually dump the module and the method the exceptional state occured in.

code:<HR>
Code:
fprintf(stderr, "ERROR: [ mcell.c::mcell_alloc( ) ] failure ...." );

4.
code:<HR>
Code:
for (st = 0; st < mcell_size(in); st++)

if mcell_size(...) returns 500000, then you will be making that call 500000 times :) unless you unroll the loops ( yikes ).

5.
code:<HR>
Code:
#ifndef MCELL_H
#define MCELL_H
#include <stdio.h>

I avoid including headers I do not have to include in any public headers. That forces the user of mcell module to include all the headers you had chosen to include ( that's a mouthful )
 
Thanks, angst. :->

> you assume that the name's scope supersets this mcell's lifetime.

Yes, I assume that the name is a string constant, or something suitably permanent. I'll make a strong note of this in the code.

> struct mcell mcell_alloc(const char *name, size_t len)
> I noticed that in most functions mcell struct is being passed in by
> value or returned as a copy of a local instance
> Have you considered returning a pointer to a heap allocated
> structure from the allocation routine?

That would improve performance (at the cost of having to eventually dereference that pointer), but by requiring a function call for every memory access, I have already thrown performance out the window. ^_^

> Using stderr for errors is actually not a bad idea, at least it
> lets me seperate true errors from other garbage my programs spit
> out to stdout. On the flipside, you terminate after every error,
> plus you mark them with keyword ( ERROR ), so there is no chance
> for confusion. Additionally, I usually dump the module and the
> method the exceptional state occured in.

Hmm... it might be a good idea to note the function and file where the error occurs, just for convenience as the code grows larger (right now, it's small enough for me to hunt down the specific phrasing of each error message). I would use stderr, but the programs I intend to write with this code will work on files provided through the commandline, not standard input and output. Hmm. I suppose it wouldn't hurt.

> if mcell_size(...) returns 500000, then you will be making that
> call 500000 times unless you unroll the loops ( yikes ).

Yes. :-> And the file compressor built with this code will be intended to work on multimegabyte files. Heh...

> I avoid including headers I do not have to include in any public
> headers. That forces the user of mcell module to include all the
> headers you had chosen to include ( that's a mouthful )

Well, including headers in other headers generally is messy, but I would prefer that there be no chance for forgetting anything.

Thanks again!
--
Stephan T. Lavavej
http://stl.caltech.edu
 
Status
Not open for further replies.