11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 10: Debugging C++ 153You know that the program is about to crash. You could understand betterwhat’s going on in the program if you could see the value of the arguments tothe function. This is the function of Add Watch. A watch displays the value ofa variable each time execution is halted. The easiest way to set a watch is toselect the variable on the display and press F4. Figure 10-6 shows a watch seton all four arguments to the function.Figure 10-6:Setting awatchallows theprogrammerto monitorthe value ofa variable.The numbers next to each name in the watch window are that variable’saddress, which aren’t of much use in this case. szTarget appears to be anempty string — this makes sense because you’ve yet to copy anything there.The value of szSource1 looks okay, but the value of szSource2 includesboth the “this is a string” and the “THIS IS A STRING” messages. Somethingseems to be amiss.The answer actually lies in the final argument. The length of the two strings isnot 16 characters but 17! The main program has failed to allocate room forthe terminating null. The program terminates as soon as you execute the firststatement within stringEmUp(), the call to strcpy().The length of a string always includes the terminating null.Now you update the program. This time, let C++ calculate the size of thestring because it just naturally includes sufficient space. The resulting programConcatenate2 works properly:// Concatenate - concatenate two strings// with a “ - “ in the middle// (this version crashes)#include #include #include #include using namespace std;void stringEmUp(char* szTarget,

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!