user2837961
user2837961

Reputation: 1555

Is this correct point to free char*

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

Upvotes: 0

Views: 106

Answers (2)

Hadi Brais
Hadi Brais

Reputation: 23719

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.

Upvotes: 1

sfjac
sfjac

Reputation: 7294

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.

Upvotes: 2

Related Questions