Re: Avoiding malloc
- From: those who know me have no need of my name <not-a-real-address@xxxxxxx>
- Date: 12 May 2006 12:31:01 GMT
in comp.lang.c i read:
Hi,
For a resource constrained embedded system I want to avoid malloc.
Currently I have various "library" modules that hide their data behind
opaque pointers. Because I read that was a good thing.
For example in the interface foo.h
typedef struct foo_t *foo_t;
foo_t fooNew(void);
Then in the implementation foo.c
struct foo_t
{
int private_field;
...
};
At startup (only) the application creates foo objects using the
function provided by the foo module:
foo_t bob = fooNew();
fooNew currently allocates storage by calling malloc, it knows how
much space to allocate since it has access to the private definition
of foo_t.
This all works well and is pretty standard stuff I think, but I now
would like to use some of these modules in a smaller system. The
provided malloc takes up too much space, both in code and data. Also
it is difficult to know ahead of time how much storage is being used
by the application.
What I would like to do is statically allocate storage at the
"application" level, instead of dynamically from inside the library
I don't mind rewriting the modules to support this. But I can't see
how to do it at all without exposing the representation of foo_t.
if you don't mind a pre-processor step to compute the size of the
foo_t:
foo.h:
#define LIBX_FOO_T_SIZE 48 /* perhaps via compiler option */
struct foo_fake { char goaway[LIBX_FOO_T_SIZE]; };
typedef struct foo_fake foo_t;
of course this implies that the implementation have the real definition and
that some tool would inspect it so as to obtain the size:
foo.c:
/* @SIZEME:FOO_T@ */ struct foo_real { /* your stuff here */ };
I think I am just going to have to put the "private" structure
definition in the interface header, but this goes against everything I
have read about.
that is often the easiest way. document that foo_t's structure isn't to be
inspected, then keep your whip handy for offenders. a mild alternative
that still exposes the data but in a round-about fashion that should help
expose code that is peeking (i.e., just search for uses of foo_real):
foo.h:
struct foo_real { /* your stuff here */ };
struct foo_fake { char goaway[sizeof(struct foo_real)]; };
typedef struct foo_fake foo_t;
either of these approaches has annoyance for your implementation -- in that
it is common to #include "foo.h" in foo.c, and thus it cannot use foo_t,
rather you would have to use struct foo_real and the occasional cast.
--
a signature
.
- References:
- Avoiding malloc
- From: John Devereux
- Avoiding malloc
- Prev by Date: Re: continue with switch
- Next by Date: Re: Avoiding malloc
- Previous by thread: Re: Avoiding malloc
- Next by thread: Help regarding Josepheus problem.
- Index(es):
Relevant Pages
|