On Wed, 10 Jan 2001, Alan Thomas wrote:
> I could not compile the code below. Thanks, Alan
> entry_var new int[size_of_entry];
> if(!entry_var)
> {
> cout << "Unable to allocate memory!";
> getch();
> exit(-1);
> }
>
> delete(entry_var);
There are several problems with your code, firstly the syntax of line
containing the new operator is wrong, correctly it would bee
int *entry_var = new int[size_of_entry];
Then again it is not advisable to use the getch() function, because it
laks the portability, some compilers like TC++ suport this one, but I
stronglly doubt that compilers from the Linux world like g++, the one
used by DevCpp will accept it.
Lastly, the code promotes a bad style, imagine that you write a program
were you allocate memory in lots of places (lines in the source code) and
you defend each allocation with a check, like you did (and you
should), this would lead to a code filled with error ckecks and still
bugy. What will you do if an allocation fails in a low level function,
because exit() will do no cleanup. Returning an error code will not solve
your problem beacuse soon you will have to face the nightmare of
errorpropagation trough different levels. The solution would be exception
handling suported by all modern compilers, like the one used by DevCpp.
Generaly it would be:
try
{
//do anything
}
catch(...) //or a more specific type
{
cerr<<"Failed to (something)"<<endl; //this can be more specific
}
You can find more info in any C++ manual.
|