[mercury-users] Filling Mercury strings in C

Ralph Becket rafe at cs.mu.OZ.AU
Wed Mar 26 09:54:13 AEDT 2003


Petr Nemec, Tuesday, 25 March 2003:
> Hello people,
>  does anybody know (sure he does :),how to fill the Mercury strings
> in C properly? I use the attached code to read a line and to destroy
> ending \n in C. But it seems the memory for the allocated strings is
> not being freed at all during the computation. Do I allocate right :)
> ?
> 
> Thanks
>  Petr
> 
> :- pred creadstring(int,string).
> :- mode creadstring(in,out) is semidet.
> 
> :-pragma
> c_code(creadstring(Pointer::in,String::out),[will_not_call_mercury],
> "
> char buffer[MAX_LINE];
> char* sDynamic;
> 
> if(fgets(buffer,MAX_LINE,(FILE*)Pointer) != NULL)
> {
>  nLength = strlen(buffer);
>  buffer[nLength-1] = '\\0';
>  sDynamic = malloc(nLength);
>  strcpy(sDynamic,buffer);
>  String = sDynamic;
>   SUCCESS_INDICATOR = 1;
> }
> else
>   SUCCESS_INDICATOR = 0;
> ").

I'm curious why you're doing this in C at all.  Have you looked at
mercury/extras/posix/posix.read.m and mercury/extras/posix/text.m?

There is also a function chomp/1 in string.m in the latest ROTD that
handles removal of any terminating '\n'.

- Ralph
--------------------------------------------------------------------------
mercury-users mailing list
post:  mercury-users at cs.mu.oz.au
administrative address: owner-mercury-users at cs.mu.oz.au
unsubscribe: Address: mercury-users-request at cs.mu.oz.au Message: unsubscribe
subscribe:   Address: mercury-users-request at cs.mu.oz.au Message: subscribe
--------------------------------------------------------------------------



More information about the users mailing list