HEAP 错误 Invalid address specified to RtlValidateHeap

HEAP error Invalid address specified to RtlValidateHeap

我的记忆有问题。我以这种方式使用结构:

Package.h 文件

#pragma once
#include <cstdlib>

struct Package {
    char *data;
    long long int *packageNumber;
    long long int *allPackages;

    Package(const int sizeOfData);
    ~Package();
};

Package.cpp

#include "Package.h"

Package::Package(const int sizeOfData) {
    void *ptr = malloc(2 * sizeof(long long int) + sizeOfData * sizeof(char));
    packageNumber = (long long int*) ptr;
    allPackages = (long long int*) ((long long int*)ptr + sizeof(long long int));
    data = (char*)((char*)ptr + 2 * sizeof(long long int));
}

Package::~Package() {
    free(data);
    free(packageNumber);
    free(allPackages);
}

并且在方法中:

for (int j = 0; j < this->bufforSize || i * bufforSize + j < allPackages; j++) {
            Package package(this->packageSize);
            this->file->read(package.data, this->packageSize);
            *package.allPackages = allPackages;
            *package.packageNumber = i * this->bufforSize + j;
            this->dataPacked->push_back(package);
        }

括号结束后抛出错误:"HEAP[zad2.exe]: Invalid address specified to RtlValidateHeap( 00000056FEFE0000, 00000056FEFF3B20 )" 我不知道我做错了什么。请帮助,迈克尔。

编辑:现在它正在为循环的第一次迭代工作。帮助我将析构函数更改为此:

Package::~Package() {
    free(packageNumber);
}

但是现在在第 2 次循环迭代中对同一个结构对象执行两次析构函数。

allPackages = (long long int*) ((long long int*)ptr + sizeof(long long int));

当你使用一个 long long int 指针(在我们的例子中它是被转换后的 ptr)并且你想增加 sizeof(long long int) 字节,你只需要做 ptr++;

但我建议您重写代码并使用 3 个 mallocs 而不是一个。

阅读freedescription:

The behavior is undefined if the value of ptr does not equal a value returned earlier by std::malloc(), std::calloc(), or std::realloc().

然后看看你的代码,注意我加的注释。

void *ptr = malloc(2 * sizeof(long long int) + sizeOfData * sizeof(char));
packageNumber = (long long int*) ptr; // you got this from malloc
allPackages = (long long int*) ((long long int*)ptr + sizeof(long long int)); // the value of this pointer is not equal to anything returned by malloc
data = (char*)((char*)ptr + 2 * sizeof(long long int)); // the value of this pointer is not equal to anything returned by malloc either

最后在析构函数中:

free(data); // was not allocated with malloc -> undefined behaviour
free(packageNumber); // was allocated with malloc -> OK
free(allPackages); // was not allocated with malloc -> undefined behaviour

您尝试删除不是从 malloc 获得的指针。这会导致未定义的行为。该错误是由于未定义的行为。请注意 free(packageNumber) 释放了 malloc 分配的整个内存块。这包括 dataallPackages 指向的内存。

有一个简单的经验法则:每次调用 malloc/calloc 时只调用一次 free。同样适用于 delete+newdelete[]+new[].