OT: What causes the Segfault in the following?

Andrew Edwards via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Aug 3 19:14:31 PDT 2017


Steven Schveighoffer wrote:
> On 8/3/17 9:12 PM, Andrew Edwards wrote:
>> Andrew Edwards wrote:
>>
>> Just in case... here are the two functions being called in main():
>>
>> https://github.com/vurtun/nuklear/blob/master/nuklear.h#L5695-L5722
>
> Can you show how you declared these in D? It's important. I think what's
> happening is that the nk_color_hex_rgb is incorrectly defined. I think
> you should *always* get segfault, with or without any of those arrays.
>
> -Steve

I certainly can, but the problem is completely in C, I'm not having any 
problems in D. In this case, I've simply copied the two functions to 
test.c and inserted main(). Here are my implementations though:

nk_color nk_rgb_hex(string rgb)
{
     if (rgb[0] == '#') rgb = rgb[1..$];
     return nk_color(cast(nk_byte)nk_parse_hex(rgb[0 .. 2]),
                     cast(nk_byte)nk_parse_hex(rgb[2 .. 4]),
                     cast(nk_byte)nk_parse_hex(rgb[4 .. $]), 255);
}

private void nk_color_hex_impl(int n)(out char[] output, nk_color col)
{
     output.reserve(n);
     alias NK_TO_HEX = (i) => i <= 9 ? '0' + i : 'A' - 10 + i;
     foreach(color; col.tupleof) {
         output ~= to!char(NK_TO_HEX((color & 0xF0) >> 4));
         output ~= to!char(NK_TO_HEX(color & 0x0F));
     }
}

void nk_color_hex_rgba(out char[] output, nk_color col)
{
     nk_color_hex_impl!8(output, col);
}

void nk_color_hex_rgb(out char[] output, nk_color col)
{
      nk_color_hex_impl!6(output, col);
}

Not to happy with nk_color_hex_impl and family yet because I'm convinced 
there is a better way but for now that's what I've got.


More information about the Digitalmars-d-learn mailing list