Version française
Home     About     Download     Resources     Contact us    
Browse thread
GC with C issues
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: ronniec95@l...
Subject: GC with C issues
Hello all,

I'm looking for some help with the following really short example when
I'm trying to reference a C allocated object from Caml (which works
fine), but the GC seems to not like it. Here's the sample code - pretty
short...


/* File: api.c */
typedef struct someObject_
{
	char* foo;
} someObject;

/*Allocate a new object*/
CAMLprim value api_newObject(value aString)
{
	CAMLparam1(aString);
	CAMLlocal1(retVal);
	someObject* x = (someObject*) malloc(1 * sizeof(someObject));
	x->foo = (char*) malloc(256 * sizeof(char));
	strcpy(x->foo, String_val(aString));
	retVal = alloc(1,Abstract_tag);
	Store_field(retVal,0,(value)x);
	fprintf(stderr,"New:%p\n",x);
	return retVal;
}
/* Print out the value */
CAMLprim value api_getValue(value inVal)
{
	CAMLparam1(inVal);
	someObject* x = NULL;
	
	x = (someObject*)Field(inVal,0);
	fprintf(stderr,"getValue called:%p",x);
	
	return copy_string(x->foo);
}
------
(* Ocaml test file main.ml *)
let _ =
    let x = Api.newObject "testString" (* New allocation everytime - leaks!*)
    in
    print_endline (Api.getValue x); (* This works fine *)
    Gc.full_major () (* This causes a segfault *)


I can't see what I'm doing wrong in the allocation? I expect this to
leak because I'm not freeing the allocated 'someObject' but I don't
expect it to segfault though?

Any help appreciated,

Ronnie