realloc 在第二次调用时失败

realloc failing on second call

我正在尝试将一组 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);

在这里,您将 realloc 返回的值分配给数据缓冲区的第一个字节。您不应该取消引用数据缓冲区。

您混淆了指针间接寻址的级别。例如,在你的行中,*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;
}

重新分配return值: “这个函数 return 是指向新分配内存的指针,如果请求失败则为 NULL。” 在第二次调用时,应该没有更多可用的 space 来重新分配...我认为最简单的方法是将其更改为: *databuffer = realloc(databuffer, total_length); if(databuffer == NULL) { *databuffer = malloc(total_length); }