Is this correct point to free char*

131 Views Asked by At

I have this code

{
 char *filename = createFilename(file, extension);
 ...
 ...
 delete[] filename;
}

inline char *DataSet::createFilename(LPCSTR file, LPCSTR extension)
{
  char *path = new char[strlen(file) + strlen(extension) + 1];
  strcpy(path, file);
  strcat(path, extension);

  return path;
}

Am I right to delete "filename" in the main function? I get ERROR_INVALID_NAME on delete. I have checked the filename and that is correct.

I know I should be using std::string but this is existing code. Please help

2

There are 2 best solutions below

0
On

If it's existing code and you can't change createFilename to return a std::string, then how about changing the call site to use std::unique_ptr. It is specialized for arrays and would be a much safer bet than doing delete on your own. See this answer.

0
On

An error of type ERROR_INVALID_NAME usually occurs when the directory name, file name or volume label is incorrect. On Windows, you might have to take care of escape sequences. For example, if the path to the file is C:\Folder\File.ext you should use the string C:\\Folder\\File.ext. In addition, some characters may not be accepted by the API you're using even though Windows allows them to be used in file and directory names. See this.