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

Tomas By tomas at basun.net
Tue Nov 18 02:48:44 AEDT 2014


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