GC seems to crash my C-code function

Steven Schveighoffer schveiguy at gmail.com
Sat Sep 18 18:43:25 UTC 2021


On 9/18/21 12:52 PM, frame wrote:
> On Saturday, 18 September 2021 at 11:47:52 UTC, Steven Schveighoffer wrote:
> 
>> Have you tried:
>>
>> ```d
>> const(char)* s2 = "...";
>> ```
>>
>> This will work because string literals are zero terminated and 
>> implicitly castable to `immutable(char)*`, which will also implicitly 
>> cast to `const(char)*`.
>>
>> That should allow s2 to be reassigned but not modify the data. IIRC, 
>> string literal data even in C is put into a read-only section by many 
>> compilers, so the code shouldn't be changing it.
> ...
>>
>> The first rule of porting -- just translate, don't change anything. I 
>> would try to do exactly what C does without using the GC at all. 
>> Continue to use malloc/free. If you have issues with type 
>> representation, you may need to adjust for that.
> 
> This is what I try to achieve - not to change much.
> But I see there is a mistake by me, s2 __is__ const in the original 
> C-code too.
> 
> Unfortunately, with `const(char)*`, `strchr()` did complain and then I 
> would have to cast it to `char*` - so I didn't used it in first place 
> because I really thought `.dup` wouldn't allocate here.

`dup` definitely allocates. But when I look at the [dlang docs for 
strchr](https://dlang.org/phobos/core_stdc_string.html#.strchr), it 
properly adds the `inout` type modifier which should correct that 
problem. Are you defining the prototype for `strchr` yourself instead of 
importing it from `core.stdc.string`?

> 
> There were also parts where the pointer is used in calculations - which 
> is accepted by the compiler - it just complains about implicitly `long` 
> to `char*` cast:
> ```
> // const char *e
> // char *w
> out[p++] = ((w - e) + 3) % 40;
> ```
> 
> Why doesn't the compiler complain about
> `char* - const(char)*`?
`long` doesn't implicitly cast to `char *`. But of course, subtracting 
two pointers works for the same base type.

Note that `long` in C is *not the same* as `long` in D.

You should take a look at 
https://dlang.org/spec/interfaceToC.html#data_type_compat

-Steve


More information about the Digitalmars-d-learn mailing list