Re: Help-a-Dummy Please
PvdG42 wrote:
I received this from a former student who obviously thinks I know more
than I do. It's a three file standard C++ Win32 console app, designed to
be put in an empty project in VS 2008 Pro. The code is short, so I'm
pasting all 3 files' content here.
Observations: Compiles with warnings about undimensioned arrays, but
appears to run OK if built in Release Mode. In Debug Mode it crashes
while exiting:
"Debug error Check Failure #2, stack around Switches is corrupt".
Any observations very much appreciated.
Your program has undefined behaviour. It can appear to "run OK", but it
doesn't. Who knows what kind of harm it is doing to your computer
unbeknownst to you...
File switches.h
#ifndef SWITCHES
#define SWITCHES
class switches
{
public:
switches(int new_numArgs, char* new_Args[]);
~switches();
void showSwitches();
private:
int numArgs;
char * Args[];
That does not look correct. An array with no size? It's basically
equivalent to
char ** Args;
(a pointer to a pointer to char).
};
#endif
File switches.cpp
#include <iostream>
#include "switches.h"
using std::cout;
using std::endl;
switches::switches(int new_numArgs, char * new_Args[])
{
numArgs = new_numArgs;
*Args = *new_Args;
Now, here you _dereference_ the 'Args' pointer that does *not* have any
valid value (yet). That's just plain wrong. I strongly recommend
abandoning the idea of using naked pointers and instead start using
standard containers. Declare 'Args' to be a vector of string objects
and initialise it correctly.
}
switches::~switches()
{
}
void switches::showSwitches()
{
for(int i = 0; i < numArgs; i++)
cout << "argv[" << i << "] = " << Args[i] << endl;
}
File main.cpp
#include <iostream>
#include "switches.h"
using std::cout;
using std::cin;
using std::endl;
int main (int argc, char* argv[])
{
switches Switches(argc, argv);
Switches.showSwitches();
for(int i = 0; i < argc; i++)
cout << "argv[" << i << "] = " << argv[i] << endl;
return 0;
}
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask