Not able to solve KlockWork Buffer Overflow error

805 Views Asked by At

I am not able to figure out the solution for this KlockWork issue.

KlockWork is showing ABV.GENERAL (1:P1) Defer for the following code

void fun1(uint32_t size)
{
  if(size > 256)
  {
    return;
  }
  uint32_t *arr = (uint32_t *)malloc(size * sizeof(uint32_t));
  if(arr == NULL)
  {
    return;
  }
  memset(arr, 0, size * sizeof(uint32_t)); 
  fun2(arr, size);
  free(arr);
}

void fun2(uint32_t *arr, uint32_t size)
{
  uint32_t i = 0;
  if(size > 256)
  {
    return;
  }
  while( i < size )
  {
    arr[i] = i;
    printf("%d", arr[i]);
    i++;
  }
}

Error: Array 'arr' of size 'size*4' may use index values(s) min(size+(-1), 255)..min(size+(-1), 255)

Please suggest some ways to avoid this error.

Thanks

1

There are 1 best solutions below

0
Luis Colorado On

In my opinion, you lack one of these header files, or the forward function prototype for the fun2 function:

#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>

void fun2(uint32_t*arr, uint32_t size);

I have compiled your code prepending all this stuff, and no warnings or errors got. Plus what I have told you in the comments to your question.