We have a module which can be used by user to store and load value of variables. Every variable has an index associated with it (in the shown code cample this is ommitted and index is instead the data type) which refers to index in data table.
Shown code below is a minimum working example of what we currently have. To store variable value user inputs data type (or variable index) and pointer to variable which he wants to store as arguemnts to write()
function.
When user wants to load value of variable he will use read()
function.
/* This is inside of module */
#include <stdint.h>
enum t {t_u8, t_s8, t_u16, t_s16, t_u32, t_s32, t_f};
static uint32_t data[7];
void write(enum t t, void *val)
{
switch (t) {
case t_u32:
case t_s32:
case t_f: data[t] = *((uint32_t *)val); break;
case t_u16:
case t_s16: data[t] = *((uint16_t *)val); break;
case t_u8:
case t_s8: data[t] = *((uint8_t *)val); break;
}
}
void read(enum t t, void *val)
{
switch (t) {
case t_u32:
case t_s32:
case t_f: *((uint32_t *)val) = *((uint32_t *)&data[t]); break;
case t_u16:
case t_s16: *((uint16_t *)val) = *((uint16_t *)&data[t]); break;
case t_u8:
case t_s8: *((uint8_t *)val) = *((uint8_t *)&data[t]); break;
}
}
/* User of module */
int main(void)
{
uint8_t u8 = 123;
int8_t s8 = -55;
uint16_t u16 = 4992;
int16_t s16 = -31829;
uint32_t u32 = 3009238113;
int32_t s32 = -123394810;
float f = -1234.99f;
write(t_u8, &u8); read(t_u8, &u8);
write(t_s8, &s8); read(t_s8, &s8);
write(t_u16, &u16); read(t_u16, &u16);
write(t_s16, &s16); read(t_s16, &s16);
write(t_u32, &u32); read(t_u32, &u32);
write(t_s32, &s32); read(t_s32, &s32);
write(t_f, &f); read(t_f, &f);
return 0;
}
We want this code to be as portable and simple and easy to understand as possible without adding a lot of complexity.
You can assume that val
will always point to variable of correct type.
What are the dangers of this code? One issue I see is that strict aliasing rule is violated multiple times. Are there any other pitfalls present? How would you change write()
and read()
functions to improve them?