C++ cstdlib abort

The C++ <cstdlib> abort function terminates the program abruptly.The declaration of the function is given below.

void abort(void);


Return type

Some points to note:

i) On executing the ‘abort’ function,for output stream buffer whether the data are flushed or the temporary files are removed is implementation-defined.The files are also not closed.

ii) The class destructor is not called if ‘abort’ is called untimely.

iii) In executing the ‘abort’ function the function pointed by the ‘atexit’ and ‘at_quick_exit’ parameter is not called.

Link: C++ cstdlib atexit

iv) An implementation-defined status to signify an ‘unsuccessful termination’ is passed to the Operating System through ‘raise(SIGABRT)‘ call.

Code example

cout<< “Testing abort” ;

abort( );

cout<< “After ‘abort’ call \n” ;

Output (In CB try pressing the ‘Build and Run’ icon)

Testing abort

“This application has requested the Runtime to terminate it in an unusual way.”

You can see that the second ‘cout’ is not executed.

A more exhaustive code example is given below.

Link :C++ cstdlib srand

Code example

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std ;

class Test
  Test( ) { cout<<“Test constructor”; }
  ~Test( ) { cout<< “Test destructor”; }

int main( )
srand( time(NULL) ) ;

long int rnd=rand( );

Test tst ; ///calls the constructor

if( rnd<200 )
cout<< rnd
  abort( ) ; ///the destructor is not called

cin.get( ) ;
return 0 ;

Output (if rnd>199)

Test constructor

This application has requested the Runtime to terminate it in an unusual way.

The destructor is never called if the ‘rnd’ value is greater than 199 and ‘abort’ is executed.This can have insidious impact on a more complex program.Say if the destructor purpose was to delete the memory allocated in heap.In such case the ‘abort’ call will produce leakage of memory in the program as no destructor will be called.For such reasons you must think thrice(not twice) before you ever try to use the ‘abort’ function in your program.

Link : C++ cstdlib rand function