Search code examples
c++templatesmallocfreememcpy

C++ malloc/memcpy/free crash


I'am really stuck with this C++ error:

    template<typename T>
    void Shift(T* Data, const ulong& Length, long Offset) const
    {
        if((!Data) || (!Length))
            return;

        if(Offset < 0)
            Offset = (Length-1) - ((-Offset-1) % Length);
        else
            Offset %= Length;

        if(!Offset)
            return;

        int TSize = sizeof(T);

        T* Shifter = new T[Length];

        if(Shifter)
        {
            memcpy(Shifter, Data + TSize * Offset, TSize * (Length - Offset));
            memcpy(Shifter + TSize * (Length - Offset), Data, TSize * Offset); //fails
            memcpy(Data, Shifter, TSize * Length);

            delete[] Shifter;
        }
    }

Well, fail is:

77CD0575 ntdll!TpWaitForAlpcCompletion() (C:\Windows\system32\ntdll.dll:??)

0028D640 ?? () (??:??)

77CB57C2 ntdll!RtlLargeIntegerDivide() (C:\Windows\system32\ntdll.dll:??)

003E1030 ?? () (??:??)

77C92A8A ntdll!RtlCopyExtendedContext() (C:\Windows\system32\ntdll.dll:??)

?? ?? () (??:??)

T is either byte of short, btw.


Solution

  • You got the pointer arithmetics wrong. Let's say:

    T* p = new T[10];
    

    To get to the n'th element, you have to use

    T* nth = p + n;
    

    In your memcpy arguments you use it like

    T* nth = p + sizeof(T) * n;
    

    which will obviously be out of bounds at times.