|
From: Ioannis V. <no...@ya...> - 2001-10-18 20:32:14
|
> -----Original Message-----
> From: dev...@li...=20
> [mailto:dev...@li...] On Behalf=20
> Of Christian Wallukat
> Sent: Thursday, October 18, 2001 2:40 PM
> To: CPP-Maillinglist (E-Mail)
> Subject: [Dev-C++] Errorhandling
>=20
>=20
> Hi list,
>=20
>=20
> I try to write a little Dos-tool.
> If I want to get the parameters and the user has no=20
> parameters specified I get an exception.
>=20
> I think the error comes if i call strlen() with an empty string...
>=20
> How can i handle this error, has anyone an idea ????
>=20
>=20
>=20
> ----------------Schnipp---------------------
> //Get commandline
> strcpy(szDatei, argv[1]);
> for (nCount =3D 2; argc > nCount; ++nCount)
> {
> strcat(szDatei, " \0");
> strcat(szDatei, argv[nCount]);
> };
>=20
> //Check Commandline
> if (strlen(szDatei) <=3D 5)=20
> {
> printf("Wrong parameter !");
> };
> -------------------Schnapp------------------
>=20
>=20
> Thanx for help
>=20
>=20
> Chris
The errors may be many. For example szDatei may not have the necessary
size to hold all these strings... Except of that, strcat(szDatei, "
\0"); is a mistake. So wwe do not know if you get an exception, the most
possible is that you get memory access error.
For more bullet proof code use C++ higher level constructs like string.
E.g.
#include <iostream>
#include <string>
...
//somewhere in a function
using namespace std;
...
if(argc>1)
string szDatei=3Dargv[1];
for (int nCount =3D 2; nCount<argc; ++nCount)
szDatei+=3D argv[nCount]);
//Check Commandline
if (szDatei.size() <=3D 5)=20
cout<<"Wrong parameter !";
This is the equivallent higher level C++ code with your mistakes
corrected (the first if statement, and int nCount in the for loop).
Ioannis
* Ioannis Vranos
* Programming pages: http://www.noicys.f2s.com
* Alternative URL: http://run.to/noicys
|