The C code snippet is exhibiting a buffer overflow vulnerability when the initial element in the array exceeds 9, which is currently not being flagged by the sonar scanner. It is advisable to implement a sonar rule addressing this issue, emphasizing the importance of not accessing memory locations outside of your allocated space.
Could you please Sonar team take a look at it?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
unsigned char first_value = 0;
void fill_array(unsigned char arr[]) {
for (int i = 0; i < 10; i++) {
arr[i] = (unsigned char)rand() % 256; // Generate random values between 0 and 255
}
}
void print_array(unsigned char arr[]) {
for (int i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
unsigned char arr[10];
srand(time(NULL)); // Seed the random number generator
fill_array(arr);
print_array(arr);
first_value = arr[0];
printf("First value: %d\n", first_value);
unsigned char * buffer = &arr[0];
buffer = buffer+1; //do not modify first element. that's why we skip it
for (int i = 1; i < first_value+1; i++) {
buffer[0] = 0; // Fill the following elements with 0; possible **BUFFER OVERFLOW!!**
buffer = buffer + 1;
}
printf("\n");
print_array(arr);
return 0;
}
I am using SonarQube EE 9.9