You're a software engineer at Arm working on firmware that reads sensor values on a Cortex-M microcontroller. This C code has been flagged in review as unsafe for a long-running embedded device.
#include <stdio.h>
#include <stdlib.h>
#define SENSOR_COUNT 8
int *readings;
void read_sensors(int *raw_values, int count) {
readings = malloc(count * sizeof(int));
for (int i = 0; i <= count; i++) {
readings[i] = raw_values[i];
}
}
int find_max_reading(int count) {
int max = 0;
for (unsigned int i = count - 1; i >= 0; i--) {
if (readings[i] > max) {
max = readings[i];
}
}
return max;
}
void report(int raw_values[SENSOR_COUNT]) {
read_sensors(raw_values, SENSOR_COUNT);
printf("max reading: %d
", find_max_reading(SENSOR_COUNT));
}
How would you rewrite the given C code? Walk through every safety and correctness problem you find and explain your approach to fixing each one.
Write a safe Python version of the logic that returns the maximum sensor reading from a fixed-size list of readings, and explain the bugs in the original code.
def max_sensor_reading(raw_values):