gpt4 book ai didi

c - realloc 在第二次调用时失败

转载 作者:行者123 更新时间:2023-12-04 02:29:04 28 4
gpt4 key购买 nike

我正在尝试将一堆 WCHAR 添加到缓冲区。这个函数就是将它添加到我的缓冲区中的原因..

DWORD add_to_buffer(BYTE *databuffer, WCHAR *path, WCHAR *value_name, DWORD type, BYTE *data, DWORD data_size, DWORD already_added) {
DWORD path_size = wcslen(path) * 2;
DWORD value_name_size = wcslen(value_name) * 2;

WCHAR *type_name = reg_type_to_wchar(type);
DWORD type_size = wcslen(type_name) * 2;


DWORD total_length = already_added + path_size + value_name_size + type_size + data_size;

*databuffer = realloc(databuffer, total_length);

CopyMemory(databuffer, path, path_size);
CopyMemory(databuffer + path_size, value_name, value_name_size);
CopyMemory(databuffer + path_size + value_name_size, type_name, type_size);
CopyMemory(databuffer + path_size + value_name_size + type_size, data, data_size);

return total_length;
}

第二次调用 add_to_buffer() 时,realloc() 失败。我基本上一遍又一遍地调用这个函数,同时向它添加信息并根据需要使其变大。我不确定如何解决此问题,因为在进入函数时 VS 中的所有内容看起来都是正确的。在此函数之外的任何地方都不会释放数据缓冲区。

最佳答案

您混淆了指针间接的级别。例如,在你的行中,*databuffer = realloc(databuffer, total_length); 你是(在左侧)取消引用 databuffer 变量但是,在调用中,你不是。

如果您希望您的函数修改指针(它确实这样做了),那么您需要将指针传递给该指针,以便修改后的值(新地址)可用于调用模块。像这样:

DWORD add_to_buffer(BYTE **databuffer, WCHAR *path, WCHAR *value_name, DWORD type, BYTE
*data, DWORD data_size, DWORD already_added) { // Pass a "databuffer" as a DOUBLE pointer
DWORD path_size = wcslen(path) * 2;
DWORD value_name_size = wcslen(value_name) * 2;

WCHAR *type_name = reg_type_to_wchar(type);
DWORD type_size = wcslen(type_name) * 2;

DWORD total_length = already_added + path_size + value_name_size + type_size + data_size;

// It is also bad practice to overwrite the argument in "realloc" calls; save to a
// temp, so that you can check for failure ...
BYTE *temp = realloc(*databuffer, total_length); // Not the "*" before databuffer!
if (temp == NULL) { // Allocation failure ...
// Here, place code to handle/signal the error
// But note that we STILL HAVE THE ORIGINAL POINTER!
return 0; // and return a value that indicates failure
}
*databuffer = temp; // Succeeded: we can now safely reassign the passed pointer.

// We now need to also dereference the double pointer in the following calls ...
CopyMemory(*databuffer, path, path_size);
CopyMemory(*databuffer + path_size, value_name, value_name_size);
CopyMemory(*databuffer + path_size + value_name_size, type_name, type_size);
CopyMemory(*databuffer + path_size + value_name_size + type_size, data, data_size);

return total_length;
}

关于c - realloc 在第二次调用时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65427068/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com