0

The following program attempts to concatenate two wstrings and a literal and convert the result to a c-style string. It fails when all this logic is placed on one line, but succeeds when the c-style conversion is on a separate line.

#include "stdafx.h"
#include <iostream>

using namespace std;

int wmain()
{
    wstring str1 = wstring(L"Example");
    wstring str2 = wstring(L"TestPath");

    // Two step construction
    wstring fullPth = wstring(str2) + wstring(L"\\") + str1;
    const wchar_t * twoStepConstruction = fullPth.c_str();

    // One step construction
    const wchar_t * oneStepConstruction = (wstring(str2) + L"\\" + str1).c_str();

    wcout << L"Two step construction yields:" << endl << twoStepConstruction
          << endl << endl;
    wcout << L"One step construction yields:" << endl << oneStepConstruction
          << endl << endl;
}

The output of this program is

Two step construction yields: TestPath\Example

One step construction yields:

Inspecting memory in the VS debugger it seems that the one-step construction leaves its pointer pointing at memory filled with EE FE repeated.

This happens in Visual Studio 2013 and Cygwin GCC 4.8.3 (GCC needs wmain changed to main).

Why does this operation fail when you put everything on one line?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Techrocket9
  • 2,026
  • 3
  • 22
  • 33

0 Answers0