-2

I've got this piece of code:

const char * c = &(4:); //This pointer contains "JPG" string

//Wide char conversion
wchar_t *cc = new wchar_t[128];
MultiByteToWideChar(CP_ACP, 0, c, -1, cc, wcslen(cc));

Then I declare a wstring variable:

wstring sFilter;
sFilter.append(L"Format: ");
sFilter.append(cc);
sFilter.push_back('\0');
sFilter.append(L"*.");
sFilter.append(cc);
sFilter.push_back('\0');
sFilter.push_back('\0');
const wchar_t * extensionFilter = sFilter.c_str();

I'm forming this wchar_t to apply a filter to GetOpenFileName function from WinApi: ofn.lpstrFilter = extensionString; which is a member of a structure.

Extension filter randomly contains: "3ormat: JPG" or ":ormat: JPG"...

I cannot change project to Unicode just because the IDE I'm working on doesn't allow it. So I need to work with this.

enter image description here

ProtectedVoid
  • 1,293
  • 3
  • 17
  • 42

1 Answers1

3
wchar_t *cc = new wchar_t[128];
MultiByteToWideChar(CP_ACP, 0, c, -1, cc, wcslen(cc));

new[] does not fill the memory that it allocates. You are calling wcslen() on a buffer that is not guaranteed to be null-terminated. And even if it were, the null would be at the front of the buffer so wcslen() would return 0. You need to pass the actual length of the allocated buffer:

MultiByteToWideChar(CP_ACP, 0, c, -1, cc, 128);

I cannot change project to Unicode just because the IDE I'm working on doesn't allow it.

You don't need to change the whole project. That only affects TCHAR-based declarations anyway. Since your input data is Ansi, you could simply call GetOpenFileNameA() directly and not worry about converting your input data to Unicode first:

const char * c = ...; //This pointer contains "JPG" string

string sFilter;
sFilter.append("Format: ");
sFilter.append(c);
sFilter.push_back('\0');
sFilter.append("*.");
sFilter.append(c);
sFilter.push_back('\0');
sFilter.push_back('\0');
const char * extensionFilter = sFilter.c_str();

OPENFILENAMEA ofn;
...
ofn.lpstrFilter = extensionFilter;
...
GetOpenFileNameA(&ofn);
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Fixed that part, but the problem isn't solved. Thanks. – ProtectedVoid Dec 10 '15 at 17:46
  • Please check this post, which I had trouble with ANSI and the solution was using Unicode: http://stackoverflow.com/questions/34201213/c-lpstr-and-string-trouble-with-zero-terminated-strings – ProtectedVoid Dec 10 '15 at 17:52
  • It seems you do not fully understanding how null-terminated strings actually work, especially in relation to `std::(w)string`. You keep misusing them, which is why you get into this kind of trouble. Your problem in the other question had NOTHING to do with Ansi vs Unicode at all (Unicode was suggested because that is what you should be using, but that is a separate issue). You were simply not managing the string data correctly to begin with. – Remy Lebeau Dec 10 '15 at 18:00