using exit(1) to return from a function - c++

linux gcc 4.4.1 C99
I am just wondering is there any advantage using the following techniques. I noticed with some code I was reading the exit number went up in value, as displayed in this code snippet.
/* This would happen in 1 function */
if(test condition 1)
{
/* something went wrong */
exit(1);
}
if(test condition 2)
{
/* something went wrong with another condition*/
exit(2);
}
or doing the following and just returning:
/* This would happen in 1 function */
if(test condition 1)
{
/* something went wrong */
return;
}
if(test condition 2)
{
/* something went wrong with another condition*/
return;
}

exit() exits your entire program, and reports back the argument you pass it. This allows any programs that are running your program to figure out why it exited incorrectly. (1 could mean failure to connect to a database, 2 could mean unexpected arguments, etc).
Return only returns out of the current function you're in, not the entire program.

return will basically return from the function and adjust the stack pointers appropriately to execute the next instructions, where as exit will cause the program itself to terminate.
using exit() in a function indicates the fatal error and program cannot recover and continue and hence, it has to be terminated.

exit will not return from a function. It will exit from the entire program

I don't think you want to exit the entire program, right?
So just returning from the function would be fine.
/* This would happen in 1 function */
if(test condition 1)
{
/* something went wrong */
return; /*return type must be void in this case */
}
if(test condition 2)
{
/* something went wrong with another condition*/
return; /*return type must be void in this case */
}
You can also explicitly specify the return type of the function and use the return value to judge whether everything went fine or not.

You're asking us whether you should return error codes from your functions?
Well that depends upon how informative you want to be to your users. If you want to act like software usually acts and pop up a modal dialog that says
Something bad happened!
Then there's no need for return codes.
If, however, you want to your software to be useful to your users and let them know what happened, then you better provide some kind of diagnostic information (error codes in the least). Then you can pop up a message that says:
I can't open "foo.bar".
Does this file exist? Do you have read access to it? Is it on a network share? Maybe I should try again?

Usually this is so that the program running your program can take some intelligent decisions.
For example if there is a wrapper script around your program foo, then it could check the
exit argument using variable $$ and change the execution path:
exec foo
if $$ eq '0':
echo "Success"
elif $$ eq '2':
exec error-recovery-script
Alternatively, you yourself can execute echo $$ to see what was the exit code from the program.

If the idea is to return the value based on the test condition, prefer using return instead of exit.
To return 1, instead of exit(1), use return 1.
Not posting the reasons, as there was a detailed discussion for the same in this link.

Related

Why nothing happens if I return EXIT_FAILURE at the end of my main function entry point in my program?

There are two macros in C++ that represent a number to return in the last line of your entry point. EXIT_FAILURE and EXIT_SUCCESS. If I return EXIT_FAILURE, which is 1, absolutely nothing happens. I explicitly wrote that the exit of my program was not successful, why is nothing happening?
The return code from your process has absolutely no effect on your process. It's only for the parent process which initiated your process to know how your run turned out.
The parent process is often the shell, though it could be any other mechanism that made the exec (or equivalent) call. Your EXIT_FAILURE indicates to the parent process that something went wrong.
For example, on the shell:
./myprog || echo "Uh oh"
Where the "Uh oh" part is only shown if the process does not return EXIT_SUCCESS (0).
A well-behaved program often logs why it had a problem, and it does it specifically to STDERR. This helps differentiate expected output from error output. This is not done for you automatically. This is entirely your responsibility.

Exiting a procedure

I have some very simple code, but I cannot figure this out. I'm calling a procedure that will (hopefully) exit the process. But it doesn't exactly do that:
procedure quit;
begin
exit;
end;
And here's where i'm calling it:
If (Ch2 = #13) and (Bar2 = 5) and (Five) Then Quit;
Bar2 is basically a byte variable that holds an array with different elements, like "display", "help", "next" and "prev", and of course, quit, Which all have their own code based on what they do.
Ch2 is a variable for ReadKey that takes in various key presses, and then allows it to do whatever is defined for that specfic command. In this case, it requires that the return key is used.
Five is a boolean operator, and is there as a prerequisite to run the quit command. I guess it isn't really necessary.
BTW, if it helps, this is a unit, not a standalone program.
Anyone know why this exit command isn't working? Hopefully this post is verbose enough.
Thank you.
The exit statement exits from the function or procedure in which it is found. It then returns execution to the calling function or procedure.
To terminate the process use halt.

How do I make my c++ code know whether a command run from "system(cmd)" failed or not?

Let's assume I am running a unix command using system("foocmd param1") on c++.
If foocmd returns "Invalid argument" back to the terminal via stderr, then how do I get my c++ code to know whether foocmd failed?
Here is my attempted solution:
My assumption is that I should check whether anything got returned to stderr by calling the command.
To do that, I tried switching over to popen. Currently, this is the way I check. I first output my stderr into a file.
sprintf(cmd, "foocmd param1 2>temp.txt");
system(cmd);
Then I check if temp.txt is empty or not.
But there has to be a better way. Can anyone lend me a hand?
The usual way is to examine the return value of system():
If it's zero, the command executed successfully and exited with a status of 0.
If it's negative, there was a problem with system() itself, and you can't assume anything.
If it's positive, then you can use WEXITSTATUS() and related macros to find out how the process exited.
See the system(3) man page for the full details.
Most of the time, you are only interested in whether the command says it succeeded:
if (!system(cmd)) {
syslog(LOG_WARNING, "Command \"%s\" failed", cmd);
/* maybe some more error handling here */
goto err_return;
}

Unhandled exception VS2010 C++

I am trying to make a socket on windows to connect to a server.
I am using the code from msdn's website, the winsock client code.
(Link: msdn.microsoft.com/en-us/library/windows/desktop/ms737591(v=vs.100).aspx )
In any case, when I try debugging said code I get the error message:
Unhandled exception at 0x58a714cf (msvcr100d.dll) in Application.exe: 0xC0000005: Access violation reading location 0x00000032.
It asks me if I want to break or continue, if I continue the same error message simply keeps popping up. If I press break it takes me to line 1643 in the file output.c .
Simply put, I have no idea about what to do to make it work, and I'd appreciate any help given.
EDIT:
A reply to all comments given thus far:
The surrounding relevant code in output.c is:
if (flags & (FL_LONG|FL_WIDECHAR)) {
if (text.wz == NULL) /* NULL passed, use special string */
text.wz = __wnullstring;
bufferiswide = 1;
pwch = text.wz;
while ( i-- && *pwch )
++pwch;
textlen = (int)(pwch - text.wz);
/* textlen now contains length in wide chars */
} else {
if (text.sz == NULL) /* NULL passed, use special string */
text.sz = __nullstring;
p = text.sz;
while (i-- && *p) //THIS IS WHERE IT BREAKS
++p;
textlen = (int)(p - text.sz); /* length of the string */
}
This is not code that I have written but innate code that already exists.
EDIT NR 2:
This is a printscreen displaying my call stack.
I do not have 10 reputation so I cannot show the image, so here is a link to the image:
http://tinypic.com/r/5n6ww9/5
On it you can see my call stack
The file output.c has the code that handles the printf family of functions.
The fact that you have an error here is probably due to a malformed printf function call in your code. Maybe you have specified an invalid print format or have not provided enough arguments.
When your program crashes, click Break and look at the call stack in the debugging windows to see where - in your code - the function is called, and with what arguments.
I suspect you are trying to print a NULL string or something. When you have found the printf call (if that's what it is), edit your question to show that section of source code and/or use the debugger to examine the variables used a arguments to the function and make sure they are all correct.
Without seeing the code that you've written, at the location of the crash, it's not possible to give a more precise answer.
Or you may insert a null string to CString.format like below:
CString str;
str.format("%s"); //A null string
where it should be
str.format("%s",mes);
where mes is char mes[20] for example
or any other variable
So the point is there may be some mistake in CString.format or Printf
Good Luck.

C++ program exited with code 0 error

I'm doing c++ at my job for the first time in years and am trying to track down a problem. I wrote code that goes out and enumerates the processes running on a machine and returns performance metrics. My problem is that some sort of unhandled error occurs and in the debug window I get a message saying the program has exited with code 0. Here is the code in the main function
int _tmain(int argc, _TCHAR* argv[])
{
while(nRun == 1)
{
try
{
WriteHeartBeat();
DoProcessLoop(dwTotalRAM, nCheckPause, oPMeter, cFileName, oProcess, oCPUUsage, nProcCount, ddsCaps2, lpDD);
CopyPerfFileToDest(cFileName);
nRun = 1;
tEnd = time(NULL);
}catch(...){
AddToLog("Error in Main Function");
}
}
AddToLog("App Stopped");
return 0;
}
The program runs for a long time but after a while it just comes back saying it exited with code 0 but that "App Stopped" line is never printed into the log. Does anyone know what kind of error I could have or what issue could be occuring? Is that try catch block sufficient enough to catch any error that could occur or is there something else I could do. Any help you could offer would be really appreciated.
EDIT: The log file should get 3 entries from here if it exits correctly. They are "Doing Process Loop" for the the "DoProcessLoop" Function, "Copying File" for the "CopyPerfFileToDest" function and the "App Stopped" if it stops correctly. When I make it stop correctly myself I get all 3 lines, when it is stopping incorrectly I only get "Doing Process Loop" in the log and then it exits with code 0. The error must be in there. I was curious if there is a generic error trap I can do to catch any all errors.
This can happen if one of functions called from _tmain called exit(0):
http://www.cplusplus.com/reference/clibrary/cstdlib/exit/
http://msdn.microsoft.com/en-us/library/6wdz5232.aspx
Sometimes files are not flushed right so if the AddToLog function defers writing to a file right before exit then it might not write out the value. You can debug the program to see if something strange is happening, or add a variable like status and set it in your catch function then return it at the end, so you know based on the value if there was an error.
Try changing the return of addtolog with a boolean and surrounding add to log with:
boolean logged=false;
while(!logged){
logged = AddToLog("App Stopped");
}
This should prevent the program from exiting until "App Stopped" is written, which may be the problem.