malloc error when trying to assign the returned pointer to a struct field
Steven Schveighoffer
schveiguy at gmail.com
Sat Sep 9 09:04:18 UTC 2023
On Friday, 8 September 2023 at 07:59:37 UTC, rempas wrote:
> I do have the following struct:
>
...
> That's some minimal code that I do have just to showcase it.
This is not ideal. Why? Because 99% of the time, a poster has
come here with a problem they don't know how to solve, and have
focused in on where they *think* the problem is. However, the
problem isn't there. But us reading the description can only see
what the poster sees, and either don't see a problem ("I'm just
as confused as you are!") or know there is more to the story.
Not only that, but frequently not-complete code is... not
complete. And people tend to focus on problems they can see (e.g.
where is that `_len` defined?), frustrating the poster with
"trivial" problems that are solved "in the real code".
Inevitably, there is a subsequent post with the real code, and
that contains the problem.
The best thing to post is a minimally reproducing example. The
next best thing is a link to a complex reproducing example. Which
you have done later (I will take a look). I just wanted to point
this out because it's a frequent problem on these forums.
> So, some times, this work will works, some others, it will give
> me the following error:
>
> `Fatal glibc error: malloc.c:2594 (sysmalloc): assertion
> failed: (old_top == initial_top (av) && old_size == 0) ||
> ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top)
> && ((unsigned long) old_end & (pagesize - 1)) == 0)`
This is an internal message from glibc. It seems the malloc
structure is corrupted.
> Is there any possible that there is a compiler bug? I do use
> ldc2 and `betterC`!
There is always a chance...
Now, critiquing your original code, I see red flags here:
> ```d
> u64 _cap = 0; // Total amount of elements (not bytes) we
> can store
> ```
and then later:
> ```d
> this(i64 size) {
> this._len = 0;
> this._cap = size;
> ```
ok, so `size` must mean the number of elements, not the number of
bytes.
> ```d
> static if (is(T == char)) { size += 1; } // Additional
> space for the null terminator
> this._ptr = cast(T*)malloc(size);
> ```
Here, you have allocated `size` bytes for the array. Is this what
is intended? Your comments suggest otherwise! If `T.sizeof` is 2
or more, then you still only allocate e.g. 20 bytes for a `_cap`
of 20. but an array of 20 T's would require 40 bytes.
-Steve
More information about the Digitalmars-d-learn
mailing list