I have a function that returns a char * pointer in C that looks like this
char * string_val (ARGS)
{
char * svalue = cJSON_GetObjectItem(nml,var_name)->valuestring;
return svalue;
}
In Fortran, I assign this to a C pointer (Using iso_c_binding)
type (c_ptr) :: C_String_ptr
...
C_String_ptr = string_val (ARGS)
This part works great. The string_val function gets called a lot, and I think it's causing a memory leak. I am trying to free the memory of the svalue pointer, but I have just run into seg faults and memory dumps. I currently have something like this:
subroutine c_mem_free (cptr) bind(C,name="c_mem_free")
use iso_c_binding
type (c_ptr) :: cptr !< The C pointer whose memory needs to be freed
end subroutine
...
call c_mem_free(C_String_ptr)
where
void c_mem_free (void** addrOfptr)
{
free(*addrOfptr); /* free the memory pointed to */
*addrOfptr=NULL; /* Nullify the pointer ;) */
}
The traceback points to a problem on the free line. I also tried passing changing cptr to value so
type (c_ptr),VALUE :: cptr
and having void*addrOfptr
and free(addrOfptr)
on the C side, but that didn't seem to work either. I've also been unsuccessful in finding the memory location of svalue on the Fortran side. If I use something like
write (6,'(z)')loc(C_String_ptr)
write (6,'(z)')loc(c_loc(C_String_ptr))
neither of these gives me the same value as when I printf the location of the memory of svalue. How can I free the memory of the pointer svalue after it's been returned in Fortran? How can I get the location of the svalue memory in Fortran?