malloc error when trying to assign the returned pointer to a struct field

rempas rempas at tutanota.com
Fri Sep 8 11:50:52 UTC 2023


On Friday, 8 September 2023 at 09:07:12 UTC, evilrat wrote:
>
> Hard to tell from that code but it is quite unlikely there is a 
> compiler bug in such simple use case.
>
> I assume you already tried debugging your program, right?

Yep! I have spent days and it's these kinds of bugs that burn me 
off and make me want to give up.

> So how about to diagnose a bit more, what if you enforce check 
> before malloc that size>0,

In the real code, there is a check! I just removed it from this 
example to make the code more clear.

> and second - from that example it is unclear how you are using 
> that struct, so maybe add else statement static assert to see 
> if it is misused somewhere else in your codebase?

That's interesting, I wasn't able to find something else! The bug 
happens when I run the testing suit and well... the tests before 
pass so I cannot find anything that goes wrong except for the 
fact that I do not free the memory that is allocated (on purpose).

But still, why would the bug be there when I assign the `_ptr` on 
the field and it won't happen if I don't assign it and just use a 
regular local variable instead (and don't assign anything to the 
`_ptr` field)?

> Also this example doesn't have len field, depending on how you 
> use with regard to cap this could be a source of problems too.

Oh right, I forgot about that! The `_len` field normally exists 
and it's it's also an unsigned 64-bit (u64) number! Yeah, the 
code is a little bit changed from the original to make it more 
simple for you guys...


More information about the Digitalmars-d-learn mailing list