HEAP错误为RtlValidateHeap指定的地址无效

时间:2015-11-09 16:05:50

标签: c++ memory-management struct memory-pool

我的记忆力很大。我这样使用struct:

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&n迭代中在同一个struct对象上执行了两次。

2 个答案:

答案 0 :(得分:3)

阅读free的{​​{3}}:

  

如果ptr的值不等于std :: malloc(),std :: calloc()或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指向的内存。

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

答案 1 :(得分:0)

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

当你使用一个long long int指针(在我们的例子中它是在播放后的ptr)并且你想要推进sizeof(long long int)字节时,你只需要做ptr ++;

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