Possibly OT: Z80/CP/M programming

From: Patrick Rigney <patrick_at_evocative.com>
Date: Mon Jan 27 12:20:00 2003

Glen wrote:
> [snip]
> requires. Except . . . how do I dynamically allocate memory? I
> don't see a
> CP/M function call to allocate or free memory. Does such a
> function exist,
> and if so, what are the details?
> Lacking such a CP/M function, how do I write replacements for malloc() and
> free()? It has to be possible or the calls would not exist in
> the library of
> the compiler I used to build the C program.


CP/M doesn't have a BDOS or BIOS function to get memory from the underlying
system, (like sbrk() on good 'ol Unix). Chances are your runtime library is
just initializing a pointer to somewhere in high RAM, and just moving it
down towards your program (or the stack) when malloc() can't satisfy a
request from its free block list.

But, I don't think you need to go that deep (assembly replacements, that
is). You can probably accomplish a good bit of your analysis just by
wrapping the library versions, and to go another step, you may even be able
to replace and optimize their functionality in these wrappers.

Writing the wrappers should be pretty straightforward. Let's say, for
example, you call yours debug_malloc() and debug_free(). Have them write
debug to a console, or just gather stats and tuck them away some place for
later retrieval by a call made less frequently. After writing the console
or whatever, do a malloc() and return the result (or do the free() if you're
in debug_free() of course). You can just write these in C. No assembly

Now the important part. Simple trick: put these replacements into a source
file *separate* from the others. Then, in your *other* source files, use a
#define to redefine malloc to your debug_malloc, such as:

#define malloc(x) debug_malloc(x)

You can easily do this in any file that the other source files #include,
just to make your life easy, but make sure you debug_malloc() source file
*doesn't* #include that file. Extra bonus: you can use an #ifdef/#endif to
enable/disable your debug replacements. You'll have to wrap any similar
calls like calloc() and strdup() if your program uses those, too.

Recompile all of your code, together with your debug_malloc().
Received on Mon Jan 27 2003 - 12:20:00 GMT

This archive was generated by hypermail 2.3.0 : Fri Oct 10 2014 - 23:36:03 BST