V
V
Victor Marquardt2016-12-10 17:49:17
C++ / C#
Victor Marquardt, 2016-12-10 17:49:17

GetModuleFileNameA, what's the problem?

There is a class with a string ResponseRequest::Path_folder() function. When building a project in MVS 2015 in debug, everything is fine and it returns the correct path to the .exe. But when I switch to release, it incorrectly calculates the path, just gives the drive letter and that's it. What can be wrong?

string ResponseRequest::Path_folder()
{
  TCHAR szPath[MAX_PATH];

  size_t sz = 0;

  sz = strlen(szPath);

  GetModuleFileNameA(NULL, szPath, MAX_PATH);

  for (size_t i = sz - 1;; i--)
  {
    if (szPath[i] == '\\')
    {
      szPath[i] = '\0';
      break;
    }
  }

  return szPath;
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
Nikolai Romanovich, 2016-12-10
@Cempl

string ResponseRequest::Path_folder()
{
  char szPath[MAX_PATH] = {}; // тут все ясно
  GetModuleFileNameA(NULL, szPath, MAX_PATH); // получаем путь
  char *lstChr = strrchr(szPath, '\\'); // указатель на последнее вхождение "\"
  *lstChr = '\0'; // заменяем на ноль (обрезаем строку)
  return szPath;
}

M
Mercury13, 2016-12-10
@Mercury13

sz = strlen(szPath);
Well, what the hell is sz equal to?
Return value
If the function succeeds, the return value is the length of the string that is copied to the buffer, in characters, not including the terminating null character. If the buffer is too small to hold the module name, the string is truncated to nSize characters including the terminating null character, the function returns nSize, and the function sets the last error to ERROR_INSUFFICIENT_BUFFER.
That's where you get the length from. Not from strlen uninitialized memory.
And the ideal would be to lay down paths longer than MAX_PATH.

1
15432, 2016-12-10
@15432

GetModuleFileNameA is the ASCII version of the function. In the Release properties, you can specify the use of Unicode, it requires the GetModuleFileNameW version of the function. In general, use GetModuleFileName without A or W.
And yes, strlen must be used after the GetModuleFileName call. And again, you need to use the TCHAR version of _tcslen for unicode compatibility

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question