c - Is there a way to restrict a pointer from being modified by specific functions? -
this builds off of previous question: is appropriate use of const qualifiers in c?
in vector.h
:
typedef struct _vector vector; vector* vector_init(const uint32 size); void* vector_get(const vector *v, uint32 idx); void vector_add(vector *v, void* const elem); void vector_set(vector *v, const uint32 idx, void* const elem); ...etc
in vector.c:
struct _vector{ uint32 used; uint32 size; void** arr; }; vector* vector_init(const uint32 size){ vector* v = malloc(sizeof(vector)); v->used = 0; v->size = size; v->arr = malloc(size*sizeof(void*)); return v; } void* vector_get(const vector *v, const uint32 idx){ if ( idx >= v->used ) exitaterror("vector","array out of bounds"); return v->arr[idx]; } void vector_add(vector *v, void* const elem){ if( v->used == v->size ) vector_resize(v); v->arr[v->used++] = elem; } ...etc
i want prevent void** arr
in _vector
being accidentally modified implementation, warning/error @ compile time. can't make arr
const void**
because don't want vector permanent, , want avoid casting away constness.
the idea here used
, size
data directly related scope of functions, whereas arr
kind of metadata don't want modify. arr
opaque, can't directly modify it, can cast or directly overwrite in bad ways such memcpy
.
in example seems unnecessary enforce access since each function straight-forward, example demonstration purposes.
i have two related questions can answered @ same time:
- is access restriction possible language support in c, , if not, opaqueness of pointer considered strong enough discouragement of directly modifying data?
- am chasing tail here , instead should focus on generating code documented , structured, wouldn't become issue?
i see related question asked in: is there way protect class variable being modified outside of function
that user seems in similar predicament in c#; question #2 relevant in scenario.
edit: think everyone's input, it's becoming clear i'm pushing language outside of original design looking type of magical keyword document things me. either hiding data behind abstraction, or structurally separating out functionality prevent temptation poke @ data, seems best solutions.
since looking solution either in c/c++, created layer of abstraction in c++ protect void** const arr
follows. please check meet requirement.
class array{ public: void setarray(void** key) { arr=key; } void** getarray() { return &(*arr); } private: void** arr; }; struct vector: public array{ int used; int size; }; vector* vector_init(const int size){ vector* v =(vector*) malloc(sizeof(vector)); v->used = 0; v->size = size; void** tem=v->getarray(); tem=(void**) malloc(size*sizeof(void*)); v->setarray(tem); return v; }
Comments
Post a Comment