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

H. S. Teoh hsteoh at qfbox.info
Fri Sep 8 19:14:47 UTC 2023


On Fri, Sep 08, 2023 at 06:59:21PM +0000, rempas via Digitalmars-d-learn wrote:
> On Friday, 8 September 2023 at 16:02:36 UTC, Basile B. wrote:
> > 
> > Could this be a problem of copy construction ?
> 
> I don't think so. The assertion seems to be violated when `malloc` is used.
> And when I assert the result in the `_ptr` field. Really weird...

The error message looks to me like a corruption of the malloc heap.
These kinds of bugs are very hard to trace, because they may go
undetected and only show up in specific circumstances, so small
perturbations of completely unrelated code may make the bug appear or
disappear -- just because the bug doesn't show up when you disable some
code does not prove that that's where the problem is; it could be that
corruption is still happening, it just so happens that it goes unnoticed
when the behaviour of the code changes slightly.

My guess is that you have a double-free somewhere, or there's a buffer
overrun. Or maybe some bad interaction with the GC, e.g. if you tried to
free a pointer from the GC heap. (Note that this may not immediately
show up; free() could've assumed that everything was OK when it has in
fact messed up its internal data structures; the problem would only show
up later on in code that's actually unrelated to the real problem.)

If I were in your shoes I'd use Valgrind / Memcheck to try to find the
real cause of the problem.  Chances are, it may have nothing to do with
the bit of code you quoted at all.  You could try to insert extra
malloc/free's in various places around the code (in places along the
code path, but unrelated to the problematic code) to see if that changes
the behaviour of the bug. If it does, your corruption is likely
somewhere other than the _ptr code you showed.


T

-- 
If the comments and the code disagree, it's likely that *both* are wrong. -- Christopher


More information about the Digitalmars-d-learn mailing list