gpt4 book ai didi

c++ - HEAP 错误 指定给 RtlValidateHeap 的地址无效

转载 作者:行者123 更新时间:2023-12-01 14:17:30 28 4
gpt4 key购买 nike

我有内存问题。我以这种方式使用结构:

包.h 文件

#pragma once
#include <cstdlib>

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

Package(const int sizeOfData);
~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);
}

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

最佳答案

阅读 descriptionfree :

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 分配的整个内存块.这包括 data 指向的内存。和 allPackages .

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

关于c++ - HEAP 错误 指定给 RtlValidateHeap 的地址无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33613246/

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