In C can a function expose memory that it ‘manageds’ at a lower level as readonly to those calling that function (exposing its address). return * const is not effective but I wondered if I was overlooking a programming tick?
Thanks.
const uint8_t * get_value(int index) { static uint8_t data[2] = {0, 0}; return (const uint8_t *)&data[index]; } int main(void) { uint8_t * value; value = get_value(1); *value += 1; return 0; }
@j_random_hacker Suggested a good compromise to my question that gives that extra barrier I’m looking for to prevent casual mis-use of that data.
typedef struct { const uint8_t * value; const uint8_t size; } readonly_t; readonly_t get_value(int index, int size) { static uint8_t data[2] = {0, 0}; uint8_t rsize; /* ... validate index, size params */ readonly_t r = { &data[index], rsize }; return r; }
It’s C! You can’t 🙂 There is always a way to circumvent it. Just make it
constand hope somebody will not change it.If you are hosting an add-in or something, you should run it in a separate process to limit its access to memory.