Check if failed to allocate memory

what i want to do is if memory allocation fails it display a message shown in the example but its not working
1
2
3
4
5
6
vehiptr = new VEHICLE[vnum];
	if(vehiptr == 0)
	{
     cout<<"Failed to Allocate Memory"<<endl;
     return main();          
 }
closed account (zb0S216C)
By default, "new" throws a "std::bad_alloc" exception on failure. If you catch the exception, you'll be able to handle the error. However, failure the catch an exception will result in program termination. Here's an example on how to handle exceptions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main( )
{
    int *BigArray_( NULL );
    try
    {
        BigArray_ = ::new int[500];
    }
    catch( std::exception const &Exception_ )
    {
        std::cout << "Error: A " << Exception_.what( ) << " was thrown\n";
        return( 1 );
    }

    delete [] BigArray_; // Forgot this :(
    return( 0 );
}

See here for more information on exceptions: http://www.cplusplus.com/doc/tutorial/exceptions/

Wazzak
Last edited on
if enter like 9999999999999999999999999
the program just ends nothing else
i want it to show some error and your code is not working
closed account (zb0S216C)
Sarmadas wrote:
"i want it to show some error"

That's your job. Use the link I provided to figure it out.

Sarmadas wrote:
"your code is not working"

It does work. If your compiler rejects it then it's obvious that your compiler is either out-of-date or doesn't comply with the C++ Standard.

Also, never, ever call "main( )".

Wazzak
Last edited on
Thanks i'm using Visual c++ 2012
closed account (zb0S216C)
Post the code you're trying to compile.

Wazzak
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#include <iostream>
#include <string>
using namespace std;
class VEHICLE{
private:
    char company[20];
    char model[20];	
	int year;
	int	engin;
public:
	VEHICLE();
	
	void display(char[],char[],int,int);
	void get_input(char[],char[],int,int);
	void set_vehicle(char[],char[],int,int);
	void get_vehicle(char[],char[],int*,int*);
	
	~VEHICLE()
	{
		
		cout<<"Object Deleted"<<endl;
	}
	
};
VEHICLE::VEHICLE()
{
	strcpy_s(company,"sarmad");
	strcpy_s(model,"ali");
	year = 0;
	engin = 0;
}

void VEHICLE::set_vehicle(char comp[],char mod[],int y,int eng)
{
	strcpy_s(company,comp);
	strcpy_s(model,mod);
	year = y;
	engin = eng;

}
void VEHICLE::get_vehicle(char comp[],char mod[],int *y,int *eng)
{
	strcpy(comp,company);
	strcpy(mod,model);
	*y = year;
	*eng = engin;

}
void VEHICLE::display(char comp[],char mod[],int y,int eng)
{
	get_vehicle(comp,mod,&y,&eng);

	cout<<"Company:  "<<comp<<endl;
	cout<<endl;
	cout<<"Model:  "<<mod<<endl;
	cout<<endl;
	cout<<"Year:  "<<y<<endl;
	cout<<endl;
	cout<<"Engin Capcity In Cc:  "<<eng<<endl;
	cout<<endl;

}
void VEHICLE::get_input(char comp[],char mod[],int y,int eng)
{
    
		cout<<"Please Enter The Name Of Vehicle Maker Company: ";
		cin>>comp;
		cout<<endl;
		cout<<"Please Enter the Model Of The Vehicle: ";
		cin>>mod;
		cout<<endl;
		cout<<"Please Enter The Year Of Registration: ";
		cin>>y;
		cout<<endl;
		cout<<"Please Enter The Engin Capacity: ";
		cin>>eng;
		cout<<endl;
		set_vehicle(comp,mod,y,eng);
	


}

int main()
{
	char comp[20];
	char mod[20];
	int y = 0;
	int eng = 0;
int vnum = 0;
	VEHICLE* vehiptr (NULL);
	cout<<"Please Enter The Number Of Vehicle: ";
	cin>>vnum;
	cout<<endl;
	try
	{
	vehiptr = new VEHICLE[vnum];
	}
	 catch(exception const &e)
	 {
		 cout << "Error: A " << e.what( ) << " was thrown"<<endl;
	 }
	for(int a=0;a<vnum;a++)
	{
	cout<<"VEHICLE "<<a+1<<endl;
	cout<<endl;
	vehiptr[a].get_input(comp,mod,y,eng);
	
	}
	for(int i =0;i<vnum;i++)
	{
	cout<<"VEHICLE ["<<i+1<<']'<<endl;
	cout<<endl;
	vehiptr[i].display(comp,mod,y,eng);

	}
	cout<<endl;
	delete [] vehiptr;
	cout<<endl;
	system("pause");

}
closed account (zb0S216C)
"strcpy_s( )" isn't a standard function -- don't use it as it's specific to Microsoft's compiler. Use "strcpy( )" instead. Other than the latter, the code compiles fine. Though, I don't know why you're using raw strings instead of "std::string".

Wazzak
Last edited on
As Framework mentioned above, use std::string for strings.

char arrays are not strings, they're char arrays; plus you're using unbounded copies into the buffers with strcpy(), you should be using strncpy().
Please i don't know about the the std::string function please give me a exapmple of code and why should i use strncpy

As Framework mentioned above, use std::string for strings.

char arrays are not strings, they're char arrays; plus you're using unbounded copies into the buffers with strcpy(), you should be using strncpy().As Framework mentioned above, use std::string for strings.

char arrays are not strings, they're char arrays; plus you're using unbounded copies into the buffers with strcpy(), you should be using strncpy().

Please explain it with an example please
Like this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#include <iostream>
#include <string>
using namespace std;
class VEHICLE{
private:
    string company;
    string model;	
	int year;
	int	engin;
public:
	VEHICLE();
	
	void display(string,string,int,int);
	void get_input(string,string,int,int);
	void set_vehicle(string,string,int,int);
	void get_vehicle(string*,string*,int*,int*);
	
	~VEHICLE()
	{
		
		cout<<"Object Deleted"<<endl;
	}
	
};
VEHICLE::VEHICLE()
{
	company = "";
	model = "";
	year = 0;
	engin = 0;
}

void VEHICLE::set_vehicle(string comp,string mod,int y,int eng)
{
	company = comp;
	model = mod;
	year = y;
	engin = eng;

}
void VEHICLE::get_vehicle(string *comp,string *mod,int *y,int *eng)
{
	*comp = company;
	*mod = model;
	*y = year;
	*eng = engin;

}
void VEHICLE::display(string comp,string mod,int y,int eng)
{
	get_vehicle(&comp,&mod,&y,&eng);

	cout<<"Company:  "<<comp<<endl;
	cout<<endl;
	cout<<"Model:  "<<mod<<endl;
	cout<<endl;
	cout<<"Year:  "<<y<<endl;
	cout<<endl;
	cout<<"Engin Capcity In Cc:  "<<eng<<endl;
	cout<<endl;

}
void VEHICLE::get_input(string comp,string mod,int y,int eng)
{
    
		cout<<"Please Enter The Name Of Vehicle Maker Company: ";
		cin>>comp;
		cout<<endl;
		cout<<"Please Enter the Model Of The Vehicle: ";
		cin>>mod;
		cout<<endl;
		cout<<"Please Enter The Year Of Registration: ";
		cin>>y;
		cout<<endl;
		cout<<"Please Enter The Engin Capacity: ";
		cin>>eng;
		cout<<endl;
		set_vehicle(comp,mod,y,eng);
	


}

int main()
{
	char comp[20];
	char mod[20];
	int y = 0;
	int eng = 0;
int vnum = 0;
	VEHICLE* vehiptr (NULL);
	cout<<"Please Enter The Number Of Vehicle: ";
	cin>>vnum;
	cout<<endl;
	try
	{
	vehiptr = new VEHICLE[vnum];
	}
	 catch(exception const &e)
	 {
		 cout << "Error: A " << e.what( ) << " was thrown"<<endl;
	 }
	for(int a=0;a<vnum;a++)
	{
	cout<<"VEHICLE "<<a+1<<endl;
	cout<<endl;
	vehiptr[a].get_input(comp,mod,y,eng);
	
	}
	for(int i =0;i<vnum;i++)
	{
	cout<<"VEHICLE ["<<i+1<<']'<<endl;
	cout<<endl;
	vehiptr[i].display(comp,mod,y,eng);

	}
	cout<<endl;
	delete [] vehiptr;
	cout<<endl;
	system("pause");

}

Last edited on
closed account (3TXyhbRD)
kbw wrote:
As Framework mentioned above, use std::string for strings.

char arrays are not strings, they're char arrays; plus you're using unbounded copies into the buffers with strcpy(), you should be using strncpy().As Framework mentioned above, use std::string for strings.

char arrays are not strings, they're char arrays; plus you're using unbounded copies into the buffers with strcpy(), you should be using strncpy().


Sarmadas wrote:
Please explain it with an example please


strcpy(dest, source) copies all characters from source to dest. Possible scenario is that source has more allocated characters than dest (e.g.: source has 100 chars and uses all of them, dest has 10 characters. 100 characters don't fit into 10 but the function will try and write past that). In this case the program behavior is undefined, it may run or it may not.

strncpy(dest, source, n) will copy, at most, n characters from source to dest, in this case you can specify to the function not to copy more than 10 characters because that's all you got room for.

A practice for using strncpy is:
1
2
3
4
5
6
7
8
9
#include <stdio.h>

int main()
{
    char dest[10], source[] = "characters go here, more than 10";
    dest[sizeof(dest) - 1] = 0;
    strncpy(dest, source, sizeof(dest) - 1);
    printf("%s\r\n", dest);
}

Output:
character

This will always work because the last character will always be NULL and any strncpy() call will copy at most sizeof(dest) - 1 characters (will not write anything on the last character).

In standard C all char arrays end with NULL (int: 0 or char: '\0'). This means that if you have a char array with the size equal to 10 you can only use, at most, 9 characters because the last one [on index 9 (size - 1)] is reserved for '\0' (assuming you want to eventually display what's in that array and use functions on char arrays).

strncpy() copies at most n characters and does not add the terminating NULL character unless it was met before going through n characters.

For instance this strncpy call will add a NULL terminating character:
1
2
char dest[10], source[] = "1234";
strncpy(dest, source, 10);

While in this case it will not:
1
2
char dest[10], source[] = "1234567890";
strncpy(dest, source, 10);


strncpy() documentation: http://www.cplusplus.com/reference/cstring/strncpy/

string documentation: http://www.cplusplus.com/reference/string/string/
Last edited on
Check this code is it good
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#include <iostream>
#include <string>
using namespace std;
class VEHICLE{
private:
    string company;
    string model;	
	int year;
	int	engin;
public:
	VEHICLE();
	
	void display(string,string,int,int);
	void get_input(string,string,int,int);
	void set_vehicle(string,string,int,int);
	void get_vehicle(string*,string*,int*,int*);
	
	~VEHICLE()
	{
		
		cout<<"Object Deleted"<<endl;
	}
	
};
VEHICLE::VEHICLE()
{
	company = "";
	model = "";
	year = 0;
	engin = 0;
}

void VEHICLE::set_vehicle(string comp,string mod,int y,int eng)
{
	company = comp;
	model = mod;
	year = y;
	engin = eng;

}
void VEHICLE::get_vehicle(string *comp,string *mod,int *y,int *eng)
{
	*comp = company;
	*mod = model;
	*y = year;
	*eng = engin;

}
void VEHICLE::display(string comp,string mod,int y,int eng)
{
	get_vehicle(&comp,&mod,&y,&eng);

	cout<<"Company:  "<<comp<<endl;
	cout<<endl;
	cout<<"Model:  "<<mod<<endl;
	cout<<endl;
	cout<<"Year:  "<<y<<endl;
	cout<<endl;
	cout<<"Engin Capcity In Cc:  "<<eng<<endl;
	cout<<endl;

}
void VEHICLE::get_input(string comp,string mod,int y,int eng)
{
    
		cout<<"Please Enter The Name Of Vehicle Maker Company: ";
		cin>>comp;
		cout<<endl;
		cout<<"Please Enter the Model Of The Vehicle: ";
		cin>>mod;
		cout<<endl;
		cout<<"Please Enter The Year Of Registration: ";
		cin>>y;
		cout<<endl;
		cout<<"Please Enter The Engin Capacity: ";
		cin>>eng;
		cout<<endl;
		set_vehicle(comp,mod,y,eng);
	


}

int main()
{
	string comp;
	string mod;
	int y = 0;
	int eng = 0;
int vnum = 0;
	VEHICLE* vehiptr (NULL);
	cout<<"Please Enter The Number Of Vehicle: ";
	cin>>vnum;
	cout<<endl;
	try
	{
	vehiptr = new VEHICLE[vnum];
	}
	 catch(exception const &e)
	 {
		 cout << "Error: A " << e.what( ) << " was thrown"<<endl;
	 }
	for(int a=0;a<vnum;a++)
	{
	cout<<"VEHICLE "<<a+1<<endl;
	cout<<endl;
	vehiptr[a].get_input(comp,mod,y,eng);
	
	}
	for(int i =0;i<vnum;i++)
	{
	cout<<"VEHICLE ["<<i+1<<']'<<endl;
	cout<<endl;
	vehiptr[i].display(comp,mod,y,eng);

	}
	cout<<endl;
	delete [] vehiptr;
	cout<<endl;
	system("pause");

}
closed account (3TXyhbRD)
It compiles and the exception handling is ok, however you are using an odd way to read/write data for each vehicle.

In your display method you already have the data your are getting with get_vehicle(). When you read data you use a method while you should read the input separately and build the vehicle from a constructor (having a default constructor can lead to invalid instances).

Instead of a display() method maybe a toString() method would be better suited since you may want to output the same vehicle to a file. If you want custom output (e.g.: each field on a different line or column) consider having getters for all your attributes e.g.:

1
2
3
4
const string& getModel() const
{
    return this.model;
}
> don't use it as it's specific to Microsoft's compiler.
That is not a good reason

> "strcpy_s( )" isn't a standard function. Use "strcpy( )" instead.
The equivalent is `strncpy()'

@OP: you're using exceptions as errors codes. The idea is that you can separate normal flow from error handling
Brothers thanks for every thing but my main topic was that
1
2
3
4
5
6
7
vehiptr = new VEHICLE[vnum];
	if(vehiptr == 0)
	{
     cout<<"Failed to Allocate Memory"<<endl;
     return main();          
 }

How do i check that if a pointer failed to allocate memory
How do i check that if a pointer failed to allocate memory


That was answered by Framework in the very first response to your original post: you have to check whether a std::bad_alloc exception was thrown.
closed account (3TXyhbRD)
Using std::nothrow to avoid exception handling is also an option: http://www.cplusplus.com/reference/new/operator%20new/
Topic archived. No new replies allowed.