保护不透明数据类型的数据

Protecting the data in opaque data types

我正在用 C 语言制作一个数据结构库,我决定让数据结构不透明,所以我有一个 header lew_arr.h

struct lew_arr;

和源文件lew_arr.c定义

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
};

这里还有一个函数的定义,它为新的 lew_arr 结构分配内存,对其进行初始化,然后 returns 通过输出参数

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

由于header中没有定义结构,用户无法访问成员;但是,他们可以通过这样的指针更改数据:

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;
 }

我知道这会是在玩火,因为用户不会知道他们正在更改什么,但是有没有办法阻止用户这样做,或者这只是您在 C 中所做的事情之一相信程序员知道他们在做什么?

the principles of C programming language 之一是“相信程序员”。虽然这个目标“在安全和安全编程社区方面已经过时”,但它仍然是 C 编程语言的精神。

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?

你必须“让”他们去做的地方。

我希望您不必真正“信任”他们,因为其他程序员会在他们的计算机上工作,而不是您的计算机,因此您的计算机应该是安全的。