[plt-scheme] malloc/free inside MzScheme
Inside PLT MzScheme, Chapter 3 Memory Allocation:
MzScheme uses both malloc and allocation functions provided by a garbage collector. Embedding/extension C/C++ code may use either allocation method, ...
Here is my program that embeds MzScheme v300.3. The intention is to get error message as UTF-16 string.
----------------------
#include <string.h>
#include <stdlib.h>
#include "PLTHOME/include/scheme.h"
Scheme_Env *e;
long write_errmsg_fun(Scheme_Output_Port *port, const char *buffer, long offset, long size, int rarely_block)
{
int i, n;
unsigned short *s;
if (!(size == 0L || size==1L && buffer[offset]=='\12'))
{
s = (unsigned short *)malloc( scheme_utf8_decode( buffer, offset, size, NULL, 0, -1, NULL, 1, 0));
n = scheme_utf8_decode( buffer, offset, size, s, 0, -1, NULL, 1, 0);
for (i=0;i<n;i++)
printf("%c", s[i]);
free( s);//error here
}
return size;
}
int char_ready_fun(Scheme_Object *port)
{return 1;}
void close_fun(Scheme_Object *port)
{}
void need_wakeup_fun(Scheme_Object *port, void *fds)
{}
Scheme_Object * make_error_port( void)
{
Scheme_Object *tmp, *result;
MZ_GC_DECL_REG(1);
tmp = scheme_make_utf8_string("<error>");
MZ_GC_VAR_IN_REG(0, tmp);
MZ_GC_REG();
result = (Scheme_Object *) scheme_make_output_port(NULL, NULL,
tmp, NULL,
&write_errmsg_fun,
&char_ready_fun,
&close_fun,
&need_wakeup_fun,
NULL, NULL, 0);
MZ_GC_UNREG();
return result;
}
void init( void)
{
scheme_set_stack_base( NULL, 1);
scheme_make_stderr = &make_error_port;
e = scheme_basic_env();
}
int main(int argc, char* argv[])
{
init( );
if (scheme_setjmp(scheme_error_buf)) {
return -1;
} else {
scheme_apply(scheme_eval_string("read-eval-print-loop", e), 0, NULL);
}
return 0;
}
----------------------
I tried this program both under Windows/MSVC and linux/gcc. Whenever the
free( s);//error here
was executed, a fatal error happens and the program exits abnormally.
Could anyone help telling what's wrong? Many thanks.
Sincerely,
Chongkai Zhu