c - 将内存公开为只读

标签 c memory-management pointers

在 C 中,函数可以将它在较低级别“管理”的内存公开为只读给那些调用该函数的人(公开其地址)。 return * const 无效,但我想知道我是否忽略了一个编程滴答?

谢谢。

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

最佳答案

是C!你不能 :) 总有办法绕过它。只需将其设为 const 并希望有人不会更改它。

如果您正在托管加载项或其他东西,您应该在单独的进程中运行它以限制它对内存的访问。

关于c - 将内存公开为只读,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/622300/

相关文章:

c# - Xamarin 内存分析器对象增长理解

c - 代码中没有错误,但是当您调试时,我收到错误(Eclipse Luna)

c - Qt C 错误重复符号 _function_names in juicy_lucy.o 和 main.o for architectures x86_64

c - 什么是 C 中指向对象类型的指针?

memory-management - 将 Box 中的大值复制到 Rust 中的 Vec 中,而不会破坏堆栈

c - 需要一个工具来检测 C 代码中的内存泄漏

c - 结构数组中的内存分配

c++ - C : copying without knowing underlying type 中的数组/指针

c++ - 指针的返回 vector ——理解

c++ - 指针类错误