>ok i dont know how to do error handling.
Error handling is application specific. As long as you check your return values and initialize your variables properly you'll have done the majority of the work. Past that it's all about how you react to an error.
Most simple programs will just bail when something unexpected happens, but for larger programs you will need to perform some form of recovery. However, this usually isn't possible at the location that the error occurs, so a good way to move up the call chain to get to a place that is prepared to handle your error would be using exceptions.
Any good book on C++ will give you more detail than I can here on exceptions, but the idea is like this (off the top of my head):
Code:
#include <cstdlib>
#include <iostream>
#include <new>
using namespace std;
namespace {
const int MAX_RECOVERY = 10;
size_t recovery_index;
int recovery[MAX_RECOVERY];
}
int main()
{
for ( int i = 0; i < 20; i++ ) {
int *p;
bool recover = false;
try {
throw bad_alloc();
p = new int;
recover = false;
}
catch ( bad_alloc& ) {
if ( recovery_index == MAX_RECOVERY ) {
cerr<<"Memory exhausted, no recovery available\n";
return EXIT_FAILURE;
}
else {
int recovery_left = sizeof *recovery * (MAX_RECOVERY - recovery_index - 1);
cerr<<"Memory exhausted, recovery available: "<< recovery_left <<" bytes\n";
p = &recovery[recovery_index++];
}
recover = true;
}
*p = i;
cout<< *p <<endl;
if ( !recover ) {
delete p;
}
}
}