GC seems to crash my C-code function

Steven Schveighoffer schveiguy at gmail.com
Sun Sep 19 02:18:20 UTC 2021


On 9/18/21 5:16 PM, frame wrote:
> On Saturday, 18 September 2021 at 18:48:07 UTC, Steven Schveighoffer wrote:
>> Did you mean "long to char" cast? In that case, yes, you have to cast it.
>>
>> Note, `out` is a keyword, it can't be used as a variable, but you 
>> probably already figured that out. But if `out` here is a `char *`, 
>> then yes, you need a cast there.
>>
> 
> Yes, of course. `out(put)` is a `char[6]` here.
> 

So here is why you need a cast:

First, the code is doing math on 2 pointers, which returns a 
`ptrdiff_t`, a.k.a. `long` in 64-bits.

Second, you are using mod 40, which is great, because D will recognize 
that the range of values must be within 40!

However, since it's signed, that's -40 to 40. Which doesn't fit in a 
`char` (which is unsigned).

D does not allow an implicit narrowing conversion. Since -40 to -1 won't 
fit into a char (dubious anyway for char to be an integer IMO), you need 
a cast.

So my recommendation is shoehorn it into ulong to take away the sign 
before the mod, or cast to char at the end. Is there any chance that `w` 
is less than `e`? if so, do NOT use the first option.

```d
// option 1
output[p++] = (ulong(w - e) + 3) % 40;
// option 2
output[p++] = cast(char)(((w - e) + 3) % 40);
```

Remember also, `char` is C's only way to say "byte". So this may just be 
data, and not unicode data. You may want to consider using `ubyte` in 
your translation instead of `char`. But wait until your code is 
compiling and working as it did in C.

-Steve


More information about the Digitalmars-d-learn mailing list