Reputation: 2205
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;
}
Upvotes: 2
Views: 328
Reputation: 12539
Memory protection is not a language construct in 'C, it is something to do with the hardware. For example, if the memory pointed to by the pointer is in some ROM area or something, writing is not possible. And on the other way round, we can even make the part of the ReadOnly at the hardware level, then you can expect some memory exception.
Upvotes: 0
Reputation: 111150
Don't return a pointer, return the pointed to object's value as in:
uint8_t get_value(int index)
{
static uint8_t data[2] = {0, 0};
return data[index];
}
Upvotes: 1
Reputation: 422016
It's C! You can't :) There is always a way to circumvent it. Just make it const
and 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.
Upvotes: 6
Reputation: 54600
Use VirtualProtect: http://msdn.microsoft.com/en-us/library/aa366898(VS.85).aspx
With PAGE_READONLY: http://msdn.microsoft.com/en-us/library/aa366786(VS.85).aspx
Upvotes: 1