Segmentation fault after having a certain number of elements in an array?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Dec 15 07:32:26 PST 2014


On 12/15/14 10:24 AM, Steven Schveighoffer wrote:

>
> A guess -- is the class instantiated in C++? if so, it probably is not
> on the D heap, and probably is not scanned during GC collections. I
> think your m_samples array is reallocated during a collection, and you
> are using dangling memory.
>
> Try GC.addRoot(this) at the start of the function, and see if it helps.

Ugh... just after saying that, I realized this will not help, because 
the memory pointed at by 'this' is not GC allocated.

You have to GC.addRoot the m_samples array data, but even when you do 
that, any time you append it may reallocate, so every time that happens, 
you must re-add the root.

But you can add the range which includes the m_samples array pointer, 
and that should solve it (you must do this when m_samples is first 
allocated, i.e. when it starts pointing at GC memory).

GC.addRange(&m_samples, sizeof(m_samples));

If that doesn't work, try this instead:

override bool onProcessSamples(const(short)[] samples)
{
     import std.stdio;
     import core.memory;
     auto tmpsamples = m_samples.ptr;
     for(int i = 0; i<samples.length; ++i)
     {
     writeln(m_samples.length);
     m_samples.length +=1;
         if(m_samples.ptr !is tmpsamples) // if pointer changed
         {
            GC.addRoot(m_samples.ptr);
            if(tmpsamples)
               GC.removeRoot(tmpsamples);
            tmpsamples = m_samples.ptr;
         }
     }
     return true;
}

-Steve


More information about the Digitalmars-d-learn mailing list