that for arrays with size sz
the last VALID index is ... sz - 1
The following code,
first illustrates the correct code
then ... the problematic code ...
with some simple debugging tactics added.
// showCmdLinePars.cpp
// an example of (desired) usage: showCmdLinePars.exe 1 2 3
// this code illustrates a commnon coding problem: array/buffer OVERflow
// (array/buffer UNDERflow, not illustrated here, also causes a similar problem)
// and ... also illustrates some simple debugging ...
#include <iostream>
using namespace std;
#define showSteps 1
// Note: the 'back-slash' at the end of each line below ... (in this macro)
// indicates to the compiler that the code is continued on the next line
#define showStep \
cout << "\nThe next value to be printed is argv[" << ctr << "] = "; \
cout << "\nPress 'Enter' to continue ... "; \
cin.get()
#define block1 1 // to EXCLUDE compiling block1 below ... change 1 to 0 here
#define block2 0
int main( int argc, char **argv )
{
// both blocks below ... illustrate a common coding error ... that the
// programmer is responsible to prevent ... 'array buffer overflow'
cout << "Firstly ... the good code ... \n\n";
cout << "code that prints out ONLY all the command line par's yields: ";
for( int ctr = 1; ctr < argc; ++ctr )
{
#if showSteps
// include this block while debugging ... to see where/why coding error
showStep;
#endif
cout << "'" << argv[ctr] << "' ";
}
cout << "\n\ncode that prints out reversed ... as above ... yields: ";
for( int ctr = argc- 1; ctr > 0; --ctr )
{
#if showSteps
// include this block while debugging ... to see where/why coding error
showStep;
#endif
cout << "'" << argv[ctr] << "' ";
}
cout << "\n\n\nNow ... the defective code ... \n\n";
#if block1
// problematic code that 'hopes' to printout ONLY all the command line par's
for( int ctr = 1; ctr <= argc; ++ctr ) // Note: should be ... ctr < argc; ...
{
// include this block while debugging ... to see where/why coding error
showStep;
cout << "'" << argv[ctr] << "' ";
}
#endif
#if block2
// problematic code that 'hopes' to printout reversed ... as above
for( int ctr = argc; ctr > 0; --ctr ) // Note: should be int ctr = argc-1;
{
// include this block while debugging ... to see where/why coding error
showStep;
cout << "'" << argv[ctr] << "' ";
}
#endif
cout << "\n\nPress 'Enter' to exit ... ";
cin.get();
return 0;
}






MultiQuote




|