[m-users.] C pointers, strings, seg fault

Tomas By tomas at basun.net
Tue Nov 18 03:50:19 AEDT 2014


So the problem seems to be the call to "intstring_c"

What am I supposed to pass as the string output parameter to a Mercury
procedure?

Since I do not know the length of the string before the call, allocating
it in advance might get awkward.

Plus I still don't understand the seg fault, as I do not use that value?



On Mon, November 17, 2014 16:48, Tomas By wrote:
> Hello,
>
> Would appreciate if somebody could explain why this code causes a
> segmentation fault.
>
> (If it looks messed up, it is because I have simplified a `real' program
> in several stages, and then experimented a bit with the procedure
> signatures. Am on very thin ice here.)
>
> /Tomas
>
>
>
> ---------- begin code ----------
> % -*- fundamental -*-
> :- module test.
> :- interface.
> :- import_module io.
> :- pred main(io::di,io::uo) is det.
> :- implementation.
> :- import_module list, string.
>
> :- pragma foreign_decl("C","void int_str_c(MR_Integer,MR_String*);").
> :- pragma foreign_decl("C","void intstring_c(MR_Integer,MR_String*);").
>
> main(!IO) :-
>   Ns = [1,2,3,4,5,6,7,8,9,10],
>   map(int_str_m,Ns,Ss),
>   write_list(Ss,"\n",write_string,!IO), io.nl(!IO).
>
> :- pragma foreign_decl("C","#define _POSIX_C_SOURCE 200809L").
> :- pragma foreign_decl("C","#include <stdlib.h>").
> :- pragma foreign_decl("C","#include <string.h>").
> :- pragma foreign_decl("C","#include <stdint.h>").
> :- pragma foreign_decl("C","#include <stdio.h>").
>
> :- pred int_str_m(int::in,string::out) is det.
> :- pragma foreign_proc("C",int_str_m(Loc::in,Str::out),
>               [will_not_call_mercury,promise_pure,thread_safe,tabled_for_io],"
> int_str_c(Loc,&Str);
> ").
>
> :- pragma foreign_decl("C","void int_str_c(MR_Integer n,MR_String* p) {
>   MR_String s;
>   char temp[1024];
>   intstring_c(n,&s);
>   sprintf(temp,\"%i\",(int)n);
>   MR_make_aligned_string_copy(*p,temp);
> }
> ").
>
> :- pragma foreign_export("C",intstring_m(in,out),"intstring_c").
> :- pred intstring_m(int,string).
> :- mode intstring_m(in,out) is det.
> intstring_m(Int,Str) :-
>   Str = string.from_int(Int).
>
> :- end_module test.
>
>





More information about the users mailing list