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

时间:2019-04-13 13:21:02

标签: c

我有以下代码:

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转换为数据,以表示相同的块?

1 个答案:

答案 0 :(得分:1)

虽然我无法解读说明,但这会回答标题:

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: %s\n", test.a, test.b);
}

int main()
{
    char *blob;
    fillAndBackupTest(&blob);
    restoreAndPrintTest(blob);
    free(blob);
    return 0;
}

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

malloc处理大小和任意数字之和(keybody?)似乎不是一个好主意,{{1 }}也无法测量二进制blob的长度。