pranathi
pranathi

Reputation: 393

Static variable resetting in C after value 0x0c

I am trying to read continuous data from remote device and I have static variable declared to receive and send ACK . Payload of 0 and 1 holds the sequence number of the data I am getting from remote device .

The problem I have is with variable fragment_num. After it reaches 0x0c it is resetting back to 0.

Its Free RTOS application . Are there any obvious reasons for a static variable to reset to 0 or is there any problem with my code ? Thanks

#define INTIAL_FRAGMENT 0x00
static uint8_t length;
static uint8_t fragment_num ;
uint8_t image[128];
download ()
{
  if(((payload[1] << 8) | (payload[0])) == INTIAL_FRAGMENT)
{
  memset(image , 0,128);
  memcpy(image , payload,(len));
  info_download();
  length = len;
  fragment_num +=1 ;
 
}

   if(((payload[1] << 8) | (payload[0])) == fragment_num)
{
  memcpy((image+length+1) , payload,(len));
  length += len;
  fragment_num ++;
  info_download();
}

Upvotes: 0

Views: 221

Answers (1)

Jeff
Jeff

Reputation: 1264

The problem is likely buffer overflow.

static uint8_t fragment_num ;
uint8_t image[128];

The compiler may have laid out fragment_num right after image in memory. If length or len is incorrect then memcpy() could write past the end of image and overwrite the value of fragment_num.

memcpy((image+length+1) , payload,(len));

I believe you want (image+length) instead of (image+length+1) here. Adding one skips a byte.

You should probably also verify len before memcpy() to make sure it doesn't overflow, e.g.:

if (len > 128)
    return -1;
memcpy(image, payload, len);
if (length + len > 128)
    return -1;
memcpy(image + length, payload, len);

Upvotes: 2

Related Questions