I have made a simple program in which I execute a program with arguments which the User inputs, but whenever I run it, it gives me the error
"Unhandled exception at 0x00f138b7 in SZP_Client.exe: 0xC0000005: Access violation writing location 0x0000000a."
My code is
char* command_text;
cout << "Enter SERVER IP Address without Port ";
cin >> command_text;
char* command_str = strdup("PServLib.exe \"127.0.0.1\" \"30760\" ");
string command_string_out_final= command_str;
command_string_out_final.append(command_text);
command_string_out_final = command_string_out_final + " \"3627\"";
system(command_string_out_final.c_str());
Why is my code throwing an Access Violation, and how do I fix it?
The culprit is cin >> command_text
. When writing to a char*
it assumes this is a char array large enough to hold the value being written. Instead it's an uninitialized char*
, so you're writing into arbitrary memory.
The simplest fix is to change command_text
into a std::string
.
char* command_text;
cout << "Enter SERVER IP Address without Port ";
cin >> command_text;
command_text
is an unintialized pointer. Why are you mixing char*
and std::string
in your code ? Just use std::string
everywhere.
char* command_text;
cin >> command_text;
This is reading into a C style string that has no space allocated for it.
It would work much better using a C++ string
std::string command_text;
cin >> command_text;
which allocates space as needed to store the input.
You probably want
string command_text;
rather than a char *
. cin
will try to put it's output into a string
, rather than a char*
.
User contributions licensed under CC BY-SA 3.0