c - 表示结构缓冲区的有效且不易出错的方法?

标签 c memory-management buffer binary-data

假设我希望符合以下结构中列出的内存模型(作为某些文件中的二进制数据):

typedef struct fileSection_s {

    unsigned int a[ 3 ];

    unsigned int b[ 3 ]; 

} fileSection_t;

有任意数量的 fileSection_t 结构,并且使用 C,我想知道一种有效且不易出错的方法:

  • 分配任意数量的 fileSection_t 结构作为缓冲区,而不采用容易出错(?)的方法,例如:
    fileSection_t** buf = (fileSection_t** ) malloc( sizeof( fileSection_t* ) * count);
    (即,尽可能避免使用双指针)
  • 使用 memcpy 将从文件读取的二进制数据的 uint8_t* 预计算段放入所述缓冲区,该缓冲区可容纳 n 数量的 fileSection_t 结构实例。
  • 稍后访问所述 fileSection_t 实例(逐一),而不是作为某些通用缓冲区类型(例如 void*uint8_t *),但作为 fileSection_t* (可能是指针算术/转换?)。

对常见方法或众所周知的“最佳实践”的解释也将受到赞赏。

我的主要目标是本质上定义某种类似于 C 的通用接口(interface),它允许我分配一些任意的类似缓冲区的对象并在其中存储我希望的任何类型的结构内存,而不会失去迭代和的灵 active 不是什么......并且也具有通过使用指针到指针机制获得的类似效果,尽管没有第二个指针。

例如,

#include <stdio.h>
#include <stdlib.h>

typedef struct fileSection_s {

    unsigned int a[ 3 ];

    unsigned int b[ 3 ]; 

} fileSection_t;

typedef struct buffer_s {

    size_t       elementSize;

    unsigned int currentLength;

    unsigned int maxLength;

    void*        mem; // or uint8_t*? 

} buffer_t;

int main( void ) {

    buffer_t* a = ( buffer_t* ) malloc( sizeof( buffer_t ) );
    a->mem = malloc( sizeof( fileSection_t ) * count );
    a->maxLength = count;
    a->currentLength = 0;
    a->elementSize = sizeof( fileSection_t );

    FILE* f = fopen( "some_binary_data", "rb");

    ...

    uint8_t* fileMemory = ( uint8_t* )malloc( size( uint8_t ) * fileSize ); // assume fileSize is obtained via ftell


    fread( fileMemory, fileSize, sizeof( uint8_t ) );

    ...
    ...


    // someOffset is obtained earlier
    memcpy( a->mem, fileMemory + someOffset, sizeof( fileSection_t ) ); 

    ...

    // now somehwere, we need to grab a section of our buffer and cast to fileSection_t. 


    return 0;
}

因此,我想要做的是获取缓冲区的一部分并以安全方式转换为指向 fileSection_t 的指针。该功能与数组完全相同,但在这种情况下获得所述功能的方法(至少据我所知)涉及使用指针算术和字节转换。

最佳答案

我不确定这是否能回答您的问题,但在 StackOverflow 上,使用 malloc 的公认做法似乎是

type *ptr = malloc(sizeof(*p))

type *array = malloc(sizeof(*array) * n)

sizeof() 中没有类型,也没有强制转换。这是使用 malloc 的最不容易出错的方法。

关于c - 表示结构缓冲区的有效且不易出错的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19301079/

相关文章:

c - 如何将链接列表转换为动态数组

c - 收到一条错误消息,指出该变量在已声明时尚未声明

c - 删除二叉搜索树中的最低值

c++ - 从 Fortran : How to deal with Dynamic memory allocation? 调用的子例程 C++

python - 处理大型 Numpy 数组的技术?

c - 哪些非 NULL 内存地址可以自由用作 C 中的错误值?

c - 在C中逐 block 读取文件

objective-c - 如何获取 Mac 操作系统的实际名称而不是版本?

node.js - 在 “new Buffer(str)” 和 “Buffer.from(str)” 之间选择

C++ cout.endl() 清除缓冲区,cout.flush() 不