Safely shutting down program from c++ function - c++

I want to make a program that will perform some math after reading from user input files.
During the reading process (a function) I want to check if the user syntax in the file is correct, otherwise I would like to shutdown the program so that the user can modify the file(s= accordingly and run it again.
The structure will be something like this:
int main(int argCount, char *args[])
{
std::string fileName = "PathOfFile";
int a = GetUserInput(fileName, variableName);
int b = GetUserInput(fileName, variableName);
// Other functions will be placed here
return 0;
}
int GetUserInput(std::string filename, std::string variableName)
{
// Some routine to read the file and find the variableName
// Some routine to check the syntax of the user input.
// Let us assume that the integers are to be fined as: variableName 1;
// and I want to check that the ; is there. Otherwise, shutdown the program.
}
How can I shutdown the program safely from the function GetUserInput? Is there any C++ to signal that the program must wrap up and exit?

There are many different ways of doing this, the differences are mostly style, personal preferences, and which parts of the C++ library you are familiar with.
The parsing function simply calls exit().
Instead of returning the int value setting, the function takes a pointer or a reference to an int value as an additional parameter and sets it, if valid. The function returns a bool, instead, to indicate whether it parsed a valid setting. main() checks the returned bool value, and itself returns from main(), ending the program.
The parsing function returns a std::optional<int>, instead, returning a std::nullopt to indicate a parsing failure. main() checks the returned value, and itself returns from main(), ending the program.
The parsing function throws an exception that gets caught in main, with the exception handler returning from main.
Each alternative has its own advantages and disadvantages. You can decide, by yourself, which approach works best for your program.

I would suggest to structure your code such that "normal shutdown" is return from main. For example like this
bool GetUserInput(const std::string file,const std::string& variablename,int& a) {
a = ... read value from file...
if (something went wrong) return false;
return true;
}
int main() {
int a;
if (! GetUserInput("file","foo",a)) return 1;
int b;
if (! GetUserInput("file","foo",b)) return 1;
}
You can consider to throw an exception when something goes wrong:
void GetUserInput(const std::string file,const std::string& variablename,int& a) {
a = ... read value from file...
if (something went wrong) throw std::runtime_error("something went wrong");
}
int main() {
int a;
GetUserInput("file","foo",a);
int b;
GetUserInput("file","foo",b);
}
This allows you to catch the exception in main and act accordingly in case you can recover from it. Also you can have different exceptions rater than only a single bool.
If you merely want to exit the program cleanly, you can use std::exit as suggested by πάντα ῥεῖ:
void GetUserInput(const std::string file,const std::string& variablename,int& a) {
a = ... read value from file...
if (something went wrong) std::exit();
}
This will safely shutdown your program (stack is unwound, ie destructors are called, files are closed properly, etc). However, this does not allow you to react on in the caller.

Related

Access variable outside try-catch block

I have the following code:
class ClassA
{
public:
ClassA(std::string str);
std::string GetSomething();
};
int main()
{
std::string s = "";
try
{
ClassA a = ClassA(s);
}
catch(...)
{
//Do something
exit(1);
}
std::string result = a.GetSomething();
//Some large amount of code using 'a' out there.
}
I would like the last line could access the a variable. How could I achieve that, given ClassA doesn't have default constructor ClassA() and I would not like to use pointers? Is the only way to add a default constructor to ClassA?
You can't or shouldn't. Instead you could just use it within the try block, something like:
try
{
ClassA a = ClassA(s);
std::string result = a.GetSomething();
}
catch(...)
{
//Do something
exit(1);
}
The reason is that since a goes out of scope after the try block referring to the object after that is undefined behavior (if you have a pointer to where it were).
If you're concerned with a.GetSomething or the assignment throws you could put a try-catch around that:
try
{
ClassA a = ClassA(s);
try {
std::string result = a.GetSomething();
}
catch(...) {
// handle exceptions not from the constructor
}
}
catch(...)
{
//Do something only for exception from the constructor
exit(1);
}
You can use some sort of optional or just use std::unique_ptr.
int main()
{
std::string s = "";
std::unique_ptr<ClassA> pa;
try
{
pa.reset(new ClassA(s));
}
catch
{
//Do something
exit(1);
}
ClassA& a = *pa; // safe because of the exit(1) in catch() block
std::string result = a.GetSomething();
//Some large amount of code using 'a' out there.
}
Of course, just extending the try block to include the usage of a is the simplest solution.
Also, if you were really planning to exit(1) or otherwise abort the program on failure then simply don't put a try block here at all. The exception will propagate up, aborting the program if it is not caught .
One alternative is to use std::optional . This is the same sort of concept as using a pointer, but it uses automatic allocation and so you are less likely to create a memory leak. This is currently experimental status; you can use boost::optional instead if your compiler doesn't have std::experimental::optional:
#include <experimental/optional>
using std::experimental::optional;
using std::experimental::in_place;
// ...
optional<ClassA> a;
try
{
a = optional<ClassA>(in_place, s);
}
catch(...)
{
// display message or something
}
std::string result;
if ( a )
result = a->GetSomething();
I'd like to reiterate though that this is a bit of a spaghetti style and it'd be better to design your code differently so you aren't continually testing whether construction succeeded or failed.
This requires ClassA be movable or copyable. The in_place is a special argument which invokes a perfect forwarding constructor for the remaining arguments. Without in_place you can only give an actual ClassA as constructor argument, it doesn't consider implicit conversions to ClassA. (This is how optional avoids the ambiguity between copy-construction and list-initialization from object of the same type).

How to make this code less memory leak prone?

As an introduction, note that I am a Java programmer still getting used to the memory management issues in C++.
We have a base class which is used to encoded objects to a string of ASCII characters. Essentially, the class is using a stringstream class member to convert different datatypes to one long string, and then returns a char* to the caller which contains the encoded object data.
In testing for memory leaks, I am seeing that the implementation we are using seems prone to create memory leaks, because the user has to always remember to delete the return value of the method. Below is an excerpt of the relevant parts of the code:
char* Msg::encode()
{
// clear any data from the stringstream
clear();
if (!onEncode()) {
return 0;
}
// need to convert stringstream to char*
string encoded = data.str();
// need to copy the stringstream to a new char* because
// stringstream.str() goes out of scope when method ends
char* encoded_copy = copy(encoded);
return encoded_copy;
}
bool Msg::onEncode(void)
{
encodeNameValue(TAG(MsgTags::TAG_USERID), companyName);
encodeNameValue(TAG(MsgTags::TAG_DATE), date);
return true;
}
bool EZXMsg::encodeNameValue(string& name, int value)
{
if(empty(value))
{
return true;
}
// data is stringstream object
data << name << TAG_VALUE_SEPARATOR << value << TAG_VALUE_PAIRS_DELIMITER;
return true;
}
char* copy(string& source) {
char *a=new char[source.length() +1];
a[source.length()]=0;
memcpy(a,source.c_str(),source.length());
return a;
}
UPDATE
Well - I should have been more accurate about how the result of encode() is consumed. It is passed to boost:async_write, and program is crashing because I believe the string goes out of scope before async_write complete. It seems like I need to copy the returned string to a class member which is alive for life time of the class which sends the message (?).
This is the way the encode() method is actually used (after I changed the return value of to string):
void iserver_client::send(ezx::iserver::EZXMsg& msg) {
string encoded = msg.encode();
size_t bytes = encoded.length();
boost::asio::async_write(socket_, boost::asio::buffer(encoded, bytes), boost::bind(&iserver_client::handle_write, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}
It looks like the proper way to do this is to maintain a queue/list/vector of the strings to async write. As noted here (and also in the boost chat_client sample). (But that is a separate issue.)
For this question:
in your copy function you return a pointer to a heap memory!So user maybe create memory leak,I think you can not use this copy function,you can do just like this in your encode func:
return data.str();
If you want to get a char*, you can use the member function of string:c_str(),
just like this:
string ss("hello world");
const char *p = ss.c_str();
If you use a stack string object you will not create memory leak,
You could just return a std::string. You have one there anyway:
string Msg::encode()
{
// clear any data from the stringstream
clear();
if (!onEncode()) {
return string{};
}
return data.str();
}
Then the caller would look like:
Msg msg;
msg.userID = 1234;
send(msg.encode().c_str());
The only way of achieving "automatic" deletion is with a stack variable (at some level) going out of scope. In fact, this is in general the only way of guaranteeing deletion even in case of an exception, for example.
As others mentioned std::string works just fine, since the char * is owned by the stack-allocated string, which will delete the char *.
This will not work in general, for example with non char * types.
RAII (Resource Acquisition is Initialization) is a useful idiom for dealing with such issues as memory management, lock acquisition/release, etc.
A good solution would be to use Boost's scoped_array as follows:
{
Msg msg;
msg.userID = 1234;
scoped_array<char> encoded(msg.encode());
send(encoded.get());
// delete[] automatically called on char *
}
scoped_ptr works similarly for non-array types.
FYI: You should have used delete[] encoded to match new char[source.length() +1]
While using a std::string works adequately for your specific problem, the general solution is to return a std::unique_ptr instead of a raw pointer.
std::unique_ptr<char[]> Msg::encode() {
:
return std::unique_ptr<char[]>(encoded_copy);
}
The user will then get a new unique_ptr when they call it:
auto encoded = msg.encode();
send(encoded.get());
and the memory will be freed automatically when encoded goes out of scope and is destroyed.

Array of functions that can be called like 'funs[1]();'

I'm working on a Visual C++ 2010 Express console application.
Before I go into detail, the summary here is: How can I make an array/list/vector of functions and call them from that array?
So I'm having a little difficulty with function pointers. I'm writing a 'Terminal' class, which in turn has a member class 'CommandMap'. The purpose of the CommandMap class is to store a vector/array of functions and the strings that represent them in another vector/array. I want the functions to be called (only) when the class calls them from the vector, but it executed only when I added it to the vector and not when trying to call it.
I tried defining a type for it:
typedef void (*CmdCallback)();
I declared a vector to contain them:
vector<string> CmdNames;
vector<CmdCallback> CmdFuncs;
I add them like so:
// Map a new command
bool CommandMap::Map(string name, CmdCallback func)
{
if (!IsNullOrSpace(name) && func != NULL)
{
if (!Exists(name))
{
CmdNames.push_back(name);
CmdFuncs.push_back(func);
return true;
}
}
return false;
}
And I try calling them like this:
// Get a command callback from its identifier
CmdCallback CommandMap::GetFunc(string name)
{
int index = IndexOf(name);
if (index == -1) return NULL;
else return CmdFuncs.at(index);
}
// If the given string is a command indentifier
// it will invoke the associated callback.
bool CommandMap::Exec(string input)
{
for each (string id in CmdStrings)
{
if (input == id)
{
CmdCallback cmd;
cmd = GetFunc(id);
cmd();
return true;
}
}
return false;
}
I tried using this:
CmdCallback SayHello()
{
cout << "Hello World!" << endl;
return NULL; // Forces me to return null, guessing since it's
// not 'void' but a 'void' pointer it must return something
}
int main(int argc, char *argv[])
{
App = new Terminal(argc, argv);
App->Commands->Map("say", SayHello);
while (!App->ExecComplete)
{
App->WaitEnter();
App->Commands->Exec("say");
App->WaitEnter();
App->ExecComplete = true;
}
return App->ExitCode;
}
This works, at first. The function gets called when I try to Map() it though. And when I Exec() "say", it finds the callback, but when it tries to call it, I get this runtime error, to which I can see no detail other than the option to break or continue. The code it gives me is.
I pretty much want to abandon my method and try a new approach, maybe I'm going the wrong way with the void pointer typedef, and I need to throw a '&' or a '*' somewhere I haven't like in the Map() argument list. Maybe a vector isn't the best way to do this either.
Basically, I am asking how I can I make an array of functions that can (and only) be called by referencing them from the array. I'm terrible with callbacks.
You can use std::functions, or, if you don't have C++11 support, boost::function. These are function object wrappers that can be easily constructed from free or member functions. You can store these in a standard library container or simple array.
If I understand correctly you actually want to declare SayHello as void SayHello() so that a pointer to SayHello has the type void (*)() (i.e. CmdCallback) which is what you need for your vector of functions.

Functions That Will Only Accept Certain Argument Values (C++)

Let me set the scene..
You can open files in a specific mode like this:
#include <fstream>
int main(){
std::fstream myfile;
myfile.open ("filename", std::ios::app);
return 0;
}
that second parameter is an enumerated type-
which is why you will get a compiler error attempting this:
#include <fstream>
int main(){
std::fstream myfile;
myfile.open ("filename", std::ios::lksdjflskdjflksff);
return 0;
}
In this example, the class doesn't have to account for the second parameter being incorrect, and the programmer never has to worry about passing in a nonsensical value.
Question: Is there a way to write functions that must take a particular type AND a particular value?
Let's say I wanted to re-implement a File Handling class similar to the one above.
The difference is I'm making the second parameter a char instead of an enumerated type.
How could I get something like this to work:
#include "MyFileHandler.h"
int main(){
MyFileHandler myfile1;
myfile.open ("filename", 'a'); //GOOD: a stands for append
myfile.open ("filename", 't'); //GOOD: t stands for truncate
myfile.open ("filename", 'x'); //COMPILER ERROR: openmode can not be the value 'x'
return 0;
}
Going beyond this, can I get the compiler to test the validity of argument values through functional means?
Example:
void IOnlyAcceptPrimeNumbers(const int & primeNumber);
int function(void);
int main(){
IOnlyAcceptPrimeNumbers(3); //GOOD: 3 is prime
IOnlyAcceptPrimeNumbers(7); //GOOD: 7 is prime
IOnlyAcceptPrimeNumbers(10); //COMPILER ERROR: 10 is not prime
IOnlyAcceptPrimeNumbers(10+1); //GOOD: 11 is prime
IOnlyAcceptPrimeNumbers(1+1+1+1); //COMPILER ERROR: 4 is not prime
IOnlyAcceptPrimeNumbers(function()); //GOOD: can this somehow be done?
return 0;
}
void IOnlyAcceptPrimeNumbers(const int & primeNumber){return;}
int function(void){return 7;}
I believe i've made it clear what I want to do and why I find it important.
Any solutions out there?
If you want compile-time checked values, you could write templates rather than function arguments:
template <char> void foo(std::string const &); // no implementation
template <> void foo<'a'>(std::string const & s) { /* ... */ }
template <> void foo<'b'>(std::string const & s) { /* ... */ }
Usage:
foo<'a'>("hello world"); // OK
foo<'z'>("dlrow olleh"); // Linker error, `foo<'z'>` not defined.
If you want an actual compiler error rather than just a linker error, you could add a static_assert(false) into the primary template.
No, if you specify that your function will take a char, it will take any char.
The "resolution" used by the compiler for checking passed arguments is the type rather than a set of possible values.
In other words, you need to use enumerations for this, or move the checking to runtime, or do something horrid like:
static void processAorT (char typ, char *fileName) { ... }
void processA (char *fileName) { processAorT ('a', fileName); }
void processT (char *fileName) { processAorT ('t', fileName); |
(not something I would advise, by the way).
Having said that, I'm not sure what you're proposing is a good idea anyway.
The compiler may be able to detect invalid constants, but won't be very successful if the parameter passed into IOnlyAcceptPrimeNumbers has come from a variable or, worse, input by a user.
The API is a contract between caller and function and, if the rules of that contract are not followed, you're free to do whatever you want, though hopefully you'd document it.
In other words, that function should begin:
void IOnlyAcceptPrimeNumbers (int num) {
if (!isPrime (num)) return;
// do something with a prime number.
}
(or the equivalent for your function that accepts a and t but not x). Doing nothing when passed invalid parameters is a reasonable strategy, as is returning an error or throwing an exception (though no doubt some would argue with this).
How you handle it is up to you, but it needs to be handled at runtime simply because the compiler doesn't have all the information.
You can only check value validity at runtime. Best you can do is use assert to stop programm execution if precondition is violated.
No. If you want to restrict the accepted arguments you need to use enums or accept an object that inherits from a specific interface (depends how sophisticated you want to make it). Enums is the common way to address this issue.
The example about the IOnlyAcceptPrimeNumbers is not well designed. If you want to achieve something similar it would be better to provide a class method that is something such as bool setNumber(int number) that will return false if the number is not prime. If you want to do it in the costructor the real alternative is to throw an exception (that is not really nice to do).
The concept is that you can not simply rely that the user will pass you only elements from a (correct) subset of the values that the parameter type allows.
While more restrictive than your requirements (this limits the values a particular type can hold), you can always try something like:
// Vowel.h
#ifndef VOWEL_H_
#define VOWEL_H_
class Vowel
{
public:
static const Vowel A;
static const Vowel E;
static const Vowel I;
static const Vowel O;
static const Vowel U;
char get() const { return value; }
private:
explicit Vowel(char c);
char value;
};
#endif /* VOWEL_H_ */
// Vowel.cpp
#include "Vowel.h"
Vowel::Vowel(char c) : value(c) {}
const Vowel Vowel::A('A');
const Vowel Vowel::E('E');
const Vowel Vowel::I('I');
const Vowel Vowel::O('O');
const Vowel Vowel::U('U');
Since the char constructor is private, only Vowel itself can construct objects from chars. All other uses are done by copy construction or copy assignment.
(I think I originally learned this technique from Scott Meyers; thank him / blame me.)

what for we have to write at the end of the function "return"? in c++

Can someone exlain me what is that "return" at the end of the function and why we have to write at the end of the main function return 0.e.g
int main()
{
.....
return 0;
}
You don't have to write return at the end of main in C++; a return value of 0 is implicit. (This is different in C, where you do have to return a value.)
What this does is return a value to the program's environment, so that it can be known whether the program succeeded (zero) or encountered some error (non-zero). Other programs, including shell scripts/batch files can use this information to make decisions, e.g. they can stop early when an error is encountered in a program they run.
All CPUs that support function calls have an instruction like RET, to explicitly return from inside the called function, back to the code that called the function. The memory address of the code to return to after the function call has already been saved in a "well know place" (e.g. the stack). The RET instruction will retrieve that memory address and point the CPU at the correct location, in order to resume executing at the code that comes after the original function call.
In c++, some functions are declared to "return" specific values (like the function main above), while other functions never return any values (those declared as having a return type of void). Its your choice how you declare the functions that you write. If the function return type is void, you would not need an explicit return statement in your code, unless you were returning prematurely, like from inside an if, else or loop. For example:
void foo(int x) {
if (x == 0)
return; // premature return to caller
int b = x*2;
// do some more stuff
// and now no need to say return, its done implicitly because we are at function end
}
However when your function is declared as having a non-void return type (for example int), then you should have an explicit return statement in the function, even if you are not returning prematurely.
int bar(int y) {
return y*7;
}
because the caller is expecting it and may assign the return value to a variable like this:
int z = bar(4);