Skip to content

env::args differs from MSVC CRT in some cases on Windows #44650

Closed
@SpaceManiac

Description

@SpaceManiac

For a command-line of the form "a/"b.exe, where a/b.exe does indeed exist, std::env::args() produces different results than argc and argv in a C++ program. Specifically, CommandLineToArgvW is returning troublesome results. It looks like the CRT and CommandLineToArgvW disagree.

  • Invocation in Command Prompt: "a/"b.exe
  • Expected arguments: [a/b.exe]
  • C++ main() arguments: [a/b.exe]
  • Result of GetCommandLineW: "a/"b.exe
  • Result of CommandLineToArgvW: [a/, b.exe]
  • Result of std::env::args(): [a/, b.exe]

Obviously, this interpretation makes no sense. env::current_exe does not seem to be affected.

A Rust program which demonstrates the mismatch:

fn main() {
    for (i, j) in std::env::args().enumerate() {
        println!("{}: {}", i, j);
    }
}

A C++ program which demonstrates the mismatch:

#include <stdio.h>
#include <windows.h>

int main(int argc, char* argv[]) {
	printf("---- argc and argv think:\n");
	for (int i = 0; i < argc; ++i) {
		printf("%i: %s\n", i, argv[i]);
	}
	
	printf("---- GetCommandLineW is:\n");
	printf("%ws\n", GetCommandLineW());
	
	printf("---- CommandLineToArgvW thinks:\n");
	LPWSTR *szArglist;
	int nArgs;
	szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
	if (szArglist == NULL) {
		wprintf(L"CommandLineToArgvW failed\n");
		return 0;
	}
	for (int i = 0; i < nArgs; i++) {
		printf("%d: %ws\n", i, szArglist[i]);
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.O-windowsOperating system: WindowsT-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions