Reputation: 466
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??
Upvotes: 1
Views: 108
Reputation: 41222
Part of the problem might be that it appears to be relying on undefined behavior. It appears (from the shown code) that frame
is never initialized. If it is a fixed size, it could be declared as:
unsigned char frame[6];
Otherwise, it may need a call to malloc
to allocate memory for it.
Upvotes: 1
Reputation: 258618
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 of unsigned char *frame;
somehow magically increases, but it doesn't.
If you're certain of the size, you need:
rf.length = 6;
rf.frame = malloc(sizeof(unsigned char) * 6); //for C
or use a std::vector
in C++.
Upvotes: 2