Pregunta

I'm having trouble passing data by reference to a given method - when the method access the data, it's corrupted, but I'm sure that when the method is called it's not (by debuggin). Here is something like the code:

//Calling code
const void* tempPointer = array.mid(readerPos,RE8K_ICDEF_HARMONICS_SIZE).constData();
const re8k_ics_harmonics* const newStruct = static_cast< const re8k_ics_harmonics* >(tempPointer);

DSInstance().updateHarmonics(*newStruct);

//method
void DataStream::updateHarmonics(const re8k_ics_harmonics &infoHarmonics, ...)
{
    //Use infoHarmonics
}

So if I use the debugger and go put a breakpoint in the "calling code" in the last line and watch what is in newStruct, I see that the data is perfect as it should be. Than the method is called and I put a new breakpoint (or go "next line") till enter the first line inside updateHarmonics, and when I see the content of infoHarmonics, I see part of the data corrupted and part of it is there.

Why is the code becoming corrupted? What should I do? :x

Additional info:

  • array is a Qt's QByteArray
  • readerPos is a int that iterates over the QByteArray from the point data should be read
  • constData() returns a const char*

Thanks,

Momergil

¿Fue útil?

Solución

QByteArray QByteArray::mid (int pos, int len = -1 ) const

This function returns object by value, so in the line

const void* tempPointer = array.mid(readerPos, 
                              RE8K_ICDEF_HARMONICS_SIZE).constData();

you are taking a pointer to temporary data. This pointer is not valid just in the next line. You should create object on the heap or use stack allocated instance, e.g:

QByteArray midQ =  array.mid(readerPos, RE8K_ICDEF_HARMONICS_SIZE);
const void* tempPointer = midQ.constData(); // pointer valid as long 
                                            // as midQ breaths
const re8k_ics_harmonics* const newStruct = 
                         static_cast< const re8k_ics_harmonics* >(tempPointer);
DSInstance().updateHarmonics(*newStruct);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top