Amazon Interview Question
Software Engineer / DevelopersA) You can catch this exception in the second function then either 1) rethrow so that the first function can catch it then deallocate appropriately 2) Catch and return an error value
B) The second function doesn't have to catch it at all. The exception would automatically be rethrow to the first function.
Guys i present a simple solution for C/C++ , it very easy in JAVA so i ma not writing for JAVA
#include <unistd.h> /* defines fork(), and pid_t. */
#include <sys/wait.h> /* defines the wait() system call. */
int status=0;
void main()
{
/* storage place for the pid of the child process, and its exit status. */
pid_t child_pid;
int child_status;
/* lets fork off a child process... */
child_pid = fork();
/* check what the fork() call actually did */
switch (child_pid)
{
case -1:/* fork() failed */
perror("fork"); /* print a system-defined error message */
exit(1);
case 0:/* fork() succeeded, we're inside the child process */
f1();
status=1;
exit(0);/* here the CHILD process exits, not the parent. */
default:/* fork() succeeded, we're inside the parent process */
wait(&child_status);/* wait till the child process exits */
if(0==status)//oops some exception occured during f1()
{
// do exception management, i mean free memory
}
}
}
Partial handling
Consider the following case:
void g()
{
throw "Exception";
}
void f() {
int* i = new int(0);
g();
delete i;
}
int main() {
f();
return 0;
}
Can you see the problem in this code ? If g throws an exception, the variable i is never deleted and we have a memory leak.
To prevent the memory leak, f() must catch the exception, and delete i. But f() can't handle the exception, it doesn't know how!
What is the solution then? f() shall catch the exception, and then rethrow it:
void g()
{
throw "Exception";
}
void f() {
int* i = new int(0)
try
{
g();
}
catch (...)
{
delete i;
throw; // This empty throw rethrows the exception we caught
// An empty throw can only exist in a catch block
}
delete i;
}
int main() {
f();
return 0;
}
There might be two solutions
1. Catch the exceptions in the function First and release the allocated memory however in practice recommended coding style is
Use auto_ptr or smart_ptr for the dynamic memory. Auto_ptr will release the memory in case of stack unwinding even in case of exceptions :)
According to me it can't be done. See http://www.research.att.com/~bs/bs_faq2.html#resume
- CyberPhoenix October 02, 2007I did not said any thing and as you might expect the interview was a complete disaster...
BEST OF LUCK TO U GUYS