Free memory from pointer to pointer

I have an application where I have a function that I want to return some data from a file and the data retrieved from the file can be different so the memory size of the variable has to be dynamic.

What I have is a function like

GetData(char **buff)
{
      // where I do something like
      // read file and fill an std:string object up

      std::string strBuff;
      While not end of file
            strBuff.append(line from file);

      // here I create new memory and pass it back from to the caller
      *buff = new char[strBuff.length()];

      strcpy(*buff, strBuff.c_str());
      
}

When I call the function it is something like:

char *buffOut = NULL;

GetData(&buffOut);

But I get an error if I try something like:

delete [] buffOut;
Or
delete[] *buffOut;

What is the correct way to delete this memory I have allocated in the GetData function?

Thanks
atomicgs12Asked:
Who is Participating?
 
phoffricConnect With a Mentor Commented:
>> *buff = new char[strBuff.length()];
    -- does not provide enough space for the null byte
>> strcpy(*buff, strBuff.c_str());
    -- overwriting the allocated buffer - resulting in heap corruption

0
 
phoffricCommented:
>> What is the correct way to delete this memory I have allocated in the GetData function?
This should work after fixing GetData
>>     delete [] buffOut;
0
 
atomicgs12Author Commented:
so your saying it should be:
*buff = new char[strBuff.length()+1];
0
 
phoffricCommented:
>>    *buff = new char[strBuff.length()+1];
    Yes, now you allocate enough room to include the terminating null byte. Now when you do your strcpy(*buff, strBuff.c_str()), where you are copying the string length +  the null byte, you are copying within the allocated region.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.