被释放的指针没有在构造函数中分配 realloc 和 malloc

Pointer being freed was not allocated with realloc and malloc in construct function

本文关键字:分配 realloc malloc 构造函数 释放 指针      更新时间:2023-10-16

我已经尝试过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));