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

H. S. Teoh hsteoh at qfbox.info
Sat Sep 9 09:56:59 UTC 2023


On Sat, Sep 09, 2023 at 09:21:32AM +0000, rempas via Digitalmars-d-learn wrote:
> On Saturday, 9 September 2023 at 08:54:14 UTC, Brad Roberts wrote:
> > I'm pretty sure this is your problem.  You're allocating size bytes
> > which is only going to work where sizeof(T) == 1.  Changing to
> > malloc(size * sizeof(T)) is likely going to work better.
> 
> Oh man!!!! That was it! I had forget about that! Funny enough, the
> reallocation tests I do letter when expanding the vector do include
> that but I had forgot to place it in the new (because I had the an old
> one and it included this) constructor I had made that only allocates
> memory!
> 
> Now, if only one could expect how and why "libc" knows that and
> doesn't just care to give me the memory I asked it for? Or it could be
> than D does something additional without telling us? Which can explain
> when this memory is only present when I assign the value to the
> "this._ptr` field!

libc doesn't know what you intended. All it knows is that you asked it
for 20 bytes (even though you actually needed 40), then later on its
internal structures are corrupted (because you thought you got 40 bytes;
storing data past the 20 bytes overwrote some of malloc's internal data
-- this is the buffer overrun / buffer overflow I referred to). So it
aborts the program instead of continuing to run in a compromised state.


T

-- 
There are four kinds of lies: lies, damn lies, and statistics.


More information about the Digitalmars-d-learn mailing list