将数据块从内存保存到字节数组,以便稍后从字节数组恢复块



我有以下代码:

typedef struct {
    struct {
        uint64_t key;
        uint64_t hash;
        uint64_t size;
        uint64_t body;
    } length;
} block_head;
-----------------------------------------------------
//Block allocation
uint64_t d1, d2, d4; //Lengths for octet strings to be saved in memory block
uint64_t d3; //just for saving a size - integer value
unsigned char **data = (unsigned char**)malloc(sizeof(block_head) + d1 + d2 + d4);
block_head *head = (block_head *)data;
head->length.key = d1;
head->length.hash = d2;
head->length.size = d3;
head->length.body = d4;
-----------------------------------------------------
//Later we fill memory of data block
// get a pointer key buffer location
unsigned char *d = (char *)data + sizeof(secure_head_t);
//Add octet string
FillData1(d);
// get a pointer to the body buffer location
unsigned char *body = (unsigned char *)data + (sizeof(block_head) + head->length.d1 + head->length.d2);
//get the length of the body free space (of a block)
int body_length = head->length.body;
//body is filled with octet string, and length is saved to body_length
FillBody2((unsigned char*)body, &body_length) 
// Advance the body pointer to the location of the remaining space, and calculate just how much room is still available.
body += body_length;
// Save another octet string to block
FillBody3((unsigned char *)data + (sizeof(block_head) + head->length.key), &body_length);

现在我需要将填充的块(unsigned char **data)保存到字节数组中,以便稍后从数组恢复到块。

我这样做,但它不起作用:

unsigned char **data = some_filled_data;
block_head *head = (block_head *)data;
// convert data to arr
unsigned char *arr = (unsigned char *)malloc( sizeof(block_head) + (head->length.key + head->length.hash + head->length.body));
memcpy(&arr, data, sizeof(block_head) + (head->length.key + head->length.hash + head->length.body));
// convert arr to data
unsigned char *data = (unsigned char*)malloc( sizeof(unsigned char) * strlen(arr));
memcpy(&data, &arr, strlen(arr));

如果我尝试使用来自 arr 的新转换块,那么我会收到一个错误,因为它构造不正确或类似的东西

我应该如何将正确的数据转换为arrarr转换为数据,以表示相同的块?

虽然我无法破译描述,但这回答了标题:

typedef struct {
    int a;
    char b[20];
} Test;
void fillAndBackupTest(char **out) {
    Test test;
    test.a = 20;
    strcpy(test.b, "Hello!");
    *out = (char*) malloc(sizeof Test);
    memcpy(*out, &test, sizeof Test);
}
void restoreAndPrintTest(char *in) {
    Test test;
    memcpy(&test, in, sizeof Test);
    printf("a: %d, b: %sn", test.a, test.b);
}
int main()
{
    char *blob;
    fillAndBackupTest(&blob);
    restoreAndPrintTest(blob);
    free(blob);
    return 0;
}
定义结构类型

TestfillAndBackupTest()创建一个结构类型,填充其字段并将其"副本"存储到它为自己分配的缓冲区中(它现在是一个char*,但实际上它很可能仍然void*(,然后restoreAndPrintTest()从此缓冲区恢复(不同的(Test实例并打印其内容。

你如何处理malloc -ing 一个大小和一些任意数字的总和 ( keybody?似乎不是一个好主意,strlen也无法测量二进制 blob 的长度。

最新更新