In a header file, I declare a struct with an array and array length like so:
typedef struct {
unsigned char *frame;
int length;
} ResponseFrame ;
extern ResponseFrame rf;
In my main file, I have the following:
ResponseFrame rf;
int main(void)
{
while(1) {
if (receive() == 0x01) {
uint8_t val;
rf.length = 6;
for(int i = 0; i < 6; i++){
val = receive();
rf.frame[i] = val;
transmit(val); // LINE 1
}
for (uint8_t i=0; i<rf.length; i++){
transmit(rf.frame[i]); // LINE 2
}
}
}
}
The array I’m receiving is
{ 00 00 FF 00 FF 00 }
The initial transmit responds with this received data [see LINE 1] .
However, when I try to transmit using the global variable rf.frame [see LINE 2], the first value is different like this —-
{ 13 00 FF 00 FF 00 }
Why is that first initial value different like this??
You never allocate any memory for
ResponseFrame.frame, so you’re running into undefined behaviour.You’re assuming that by doing
rf.length = 6;, the size ofunsigned char *frame;somehow magically increases, but it doesn’t.If you’re certain of the size, you need:
or use a
std::vectorin C++.