Search code examples
c++pointersfreerealloc

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


I tried dataPoolBuffer = realloc(dataPoolBuffer, sizeof(char)*(dataPoolSize)); already, but Xcode reports:assigning to 'char *' from imcompatible type 'void'.

I create a class:

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();
}

};

Every time when we call .add function, it will realloc memory for the variable. However, when I do that in main():

char data[] = "0123456789";
char data2[] = "01234567890123456789";
solutionBuffer buffer;
buffer.add(data, 10);
buffer.add(data2, 20);

The xoce shows:pointer being freed was not allocated in ~solutionBuffer() when it was trying to free dataPoolBuffer . Why it does like that? How to fix that ?


Solution

  • According to the documentation,

    realloc(dataPoolBuffer, sizeof(char)*(dataPoolSize));
    

    reallocates dataPoolBuffer, but doesn't change where dataPoolBuffer points. So odds are pretty good that dataPoolBuffer is now pointing to invalid memory.

    dataPoolBuffer = (char*)realloc(dataPoolBuffer, sizeof(char)*(dataPoolSize));
    

    will do you what you want, but rethink how you are doing this. You're setting yourself up for a lot of pain. Your class violates The Rule of Three, for one thing. std::vector will handle all of container resizing and memory management for you with no muss and no fuss.