10

I want my function to return a BYTE array. The function is as follows.

BYTE sendRecieveData(BYTE control, unsigned int value){

//Open connection to LAC
HANDLE LACOutpipe;
HANDLE LACInpipe;
LACOutpipe=openConnection(MP_WRITE);
LACInpipe=openConnection(MP_READ);

//declare variables
BYTE bufDataOut[3];
BYTE bufDataIn[3];
DWORD bufInProcess;
DWORD bufOutProcess;


//sets CONTROL
bufDataOut[0]=control;

//sets DATA to be sent to LAC
BYTE low_byte = 0xff & value;
BYTE high_byte = value >> 8;
bufDataOut[1]=low_byte;
bufDataOut[2]=high_byte;

MPUSBWrite(LACOutpipe,bufDataOut,3,&bufOutProcess,1000);
MPUSBRead(LACInpipe,bufDataIn,3,&bufInProcess,1000);
MPUSBClose(LACOutpipe);
MPUSBClose(LACInpipe);

return bufDataIn[3];
}

It doesn't return a byte array and when I change BYTE to BYTE[] or BYTE[3] it gives me an error.

2 Answers 2

10

return bufDataIn[3]; means "return 4th element of bufDataIn array" and in this case it leads to undefined behaviour since the size of this array is 3.

You can allocate memory for this new array in the body of your function and return pointer to its first element:

BYTE* createArray(...)
{
    BYTE* bufDataOut = new BYTE[3];
    ....
    return bufDataOut;
}

Don't forget to delete it when you finish with it:

{
    BYTE* myArray = createArray(...);
    ...
    delete[] myArray;
}

Even better, use std::vector<BYTE> and get rid of this ugly memory management with it ;) This ensures that the memory is properly freed on any return path, even when exceptions are thrown.

Sign up to request clarification or add additional context in comments.

1 Comment

Please swap "you should" with "you can"... very good answer overall. +1
4

Since your array is relatively small I'd recommend to pass your buffer as a function argument.

void sendRecieveData(BYTE control, unsigned int value, BYTE (&buffdataIn)[3] ).

Now, one will use this function as follows:

BYTE result[3] = {0};
sendRecieveData(3, 0, result);

This way you may avoid usage of dynamic memory allocation and make your code safer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.