Search code examples
copaque-types

Protecting the data in opaque data types


I am making a data structure library in C, and I have decided to make the data structures opaque, so I have a header lew_arr.h

struct lew_arr;

and the source file lew_arr.c with the definition

struct lew_arr {
    void *buff; 
    size_t len; //number of elements in the array 
    size_t cap; //capacity of the array
    size_t sz; //number of bytes for each element
};

Also here is the definition for a function that allocates memory for a new lew_arr struct, initializes it, and returns it through through the out argument

lew_err lew_arr_init(size_t const cap, size_t const sz, struct lew_arr **out_arr);

Because the structure is not defined in the header, the user cannot access the members; however, they could change the data through pointers like this:

int main(void)
{
    struct lew_arr *a;
    lew_arr_init(10, sizeof(int), &a);
    
    char *ptr = (void *) a;
    *ptr++ = 1;
    *ptr++ = 2;
    //etc.
    return 0;
 }

I know this would be playing with fire, as the user would not know what they are changing, but is there a way to prevent the user from doing this, or is this just one of things in C where you have to trust that the programmer knows what they are doing?


Solution

  • One of the principles of C programming language is "Trust the programmer". While this goal is "outdated in respect to the security and safety programming communities", still it's the spirit of C programming language.

    is there a way to prevent the user from doing this,

    No.

    or is this just one of things in C where you have to trust that the programmer knows what they are doing?

    Where you have to "let" them do it.

    I would expect that you don't really have to "trust" them, because other programmers will work on their computers, not yours, so your computer should be safe.