Is this correct point to free char*

105 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 answers

0
sfjac 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
Hadi Brais 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.