We help IT Professionals succeed at work.

Free memory from pointer to pointer

atomicgs12
atomicgs12 asked
on
Medium Priority
412 Views
Last Modified: 2013-12-27
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
Comment
Watch Question

CERTIFIED EXPERT
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
CERTIFIED EXPERT

Commented:
>> What is the correct way to delete this memory I have allocated in the GetData function?
This should work after fixing GetData
>>     delete [] buffOut;

Author

Commented:
so your saying it should be:
*buff = new char[strBuff.length()+1];
CERTIFIED EXPERT

Commented:
>>    *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.
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.