被释放的指针没有在构造函数中分配 realloc 和 malloc
Pointer being freed was not allocated with realloc and malloc in construct function
我已经尝试过dataPoolBuffer = realloc(dataPoolBuffer, sizeof(char)*(dataPoolSize));
,但是 Xcode 报告:从不兼容的类型"void"分配给"char *"。
我创建一个类:
class solutionBuffer{
private:
char * dataPoolBuffer;
char * consumerBuffer;
char * flagBuffer;
int dataPoolSize;
int consumerBufferSize;
mutex safe;
public:
solutionBuffer(){
safe.lock();
dataPoolSize = 0;
consumerBufferSize = 0;
dataPoolBuffer = (char*)malloc(sizeof(char)*1);
consumerBuffer = (char*)malloc(sizeof(char)*1);
flagBuffer = (char*)malloc(sizeof(char)*1);
}
int add(char* data, int length)
{
dataPoolSize += length;
realloc(dataPoolBuffer, sizeof(char)*(dataPoolSize));
realloc(flagBuffer, sizeof(char)*(dataPoolSize));
memcpy(dataPoolBuffer + dataPoolSize - length, data, sizeof(char)*(length));
return 0;
}
~solutionBuffer(){
printf("%d",strlen(dataPoolBuffer));
free(dataPoolBuffer);
free(consumerBuffer);
free(flagBuffer);
safe.unlock();
}
};
每次我们调用.add
函数时,它都会为变量realloc
内存。但是,当我在main()
这样做时:
char data[] = "0123456789";
char data2[] = "01234567890123456789";
solutionBuffer buffer;
buffer.add(data, 10);
buffer.add(data2, 20);
xoce 显示:当它试图释放dataPoolBuffer
时,未在~solutionBuffer()
中分配被释放的指针。为什么会这样?如何解决?
根据文档,
realloc(dataPoolBuffer, sizeof(char)*(dataPoolSize));
重新分配dataPoolBuffer
,但不会更改dataPoolBuffer
指向的位置。因此,dataPoolBuffer
现在指向无效内存的可能性很大。
dataPoolBuffer = (char*)realloc(dataPoolBuffer, sizeof(char)*(dataPoolSize));
会做你想做的事,但要重新考虑你是如何做到的。你正在让自己承受很多痛苦。一方面,你的班级违反了三法则。std::vector 将为您处理所有容器大小调整和内存管理,无需费力,也无需大惊小怪。
当你调用realloc()
时,你需要将结果赋值回指针变量。 realloc()
通常需要将内存移动到新位置,然后返回该位置。您的代码使变量指向旧位置,并且当您在此之后尝试使用它时,您将获得未定义的行为。
所以它应该是:
dataPoolBuffer = (char*)realloc(dataPoolBuffer, sizeof(char)*(dataPoolSize));
flagBuffer = (char*)realloc(flagBuffer, sizeof(char)*(dataPoolSize));
相关文章:
- 将数组的地址分配给变量并删除
- vector.resize()中的分配错误
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- Win32编译器选项和内存分配
- 函数中堆分配的效果与缺少堆分配的情况
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 获取字符串的长度并将其分配给数组
- 使用new时如何重新分配dyyanmic数组,不使用realloc删除C++?
- 无论如何如何重新分配内存,即使 realloc() 在 c++ 中失败
- Realloc():即使使用malloc()分配内存,旧大小也无效
- 如果Malloc无法分配X字节,我应该使用Realloc还是再次使用Malloc?C++
- 使用realloc可以安全地重新分配琐碎的可复制对象的存储吗
- 如果正在缩小已分配的内存大小,请同时检查realloc()
- 无效的free() / delete / delete[] / realloc(), 4 字节在大小为 16 的块内分配
- C++:使用动态内存分配编写类似于 C realloc() 函数的函数(即更改其大小)
- 我可以使用std::realloc来防止冗余内存分配吗
- Realloc()问题,未分配
- 动态内存分配-相当于C++中的Realloc
- 被释放的指针没有在构造函数中分配 realloc 和 malloc