// String Overflow.  Author: Tom Horton, FAU CSE Dept.

#define MAXCSTRLEN 16

#include <iostream.h>
#include <string>	// include for C++ standard string class
#include <string.h>	// include for standard C string library
using namespace std;

int main()
{
  // declare some C strings
  char cString1[MAXCSTRLEN], cString2[MAXCSTRLEN], cString3[MAXCSTRLEN];

  // declare some C++ strings
  string string1 = "Nutcracker",
    string2 = "Sleeping Beauty",
    string3 = "Sleeping Ugly";

  strcpy(cString1, "Nutcracker");
  strcpy(cString2, "Sleeping Beauty");
  strcpy(cString3, "Sleeping Ugly");

  cout << "** Initial values" << endl;
  cout << "C++ strings: " << string1 << "  " << string2
       << "  " << string3 << endl;
  cout << "C strings:   " << cString1 << "  " << cString2
       << "  " << cString3 << endl;

  cout << "** Values after assigning long string to 2nd string" << endl;
  string2 =        "123456789012345678901234567890";
  strcpy(cString2, "123456789012345678901234567890");
  cout << "C++ strings: " << string1 << "  " << string2
       << "  " << string3 << endl;
  cout << "C strings:   " << cString1 << "  " << cString2
       << "  " << cString3 << endl;
}

/*
Step 1. Oh no!  Something went wrong in this code.  Explain exactly what you 
        see in the output that indicates that a run-time error has happened. 
        (Don't explain why it happened.)

Step 2. Exactly what caused this error to occur in the C code?  Be specific.

Step 3. What can you conclude about the addresses in memory where the strings 
        cString1 and cString2 are located? (Note that the compiler locates 
        variables in memory in ways that might not make sense to you, but 
        make sense to it.)

The Important Lesson: C-style strings can be dangerous because C and C++ 
perform no run-time checks to see if you are unintentionally clobbering 
memory values outside of the string array that you are modifying. Good C 
programmers use the function strncpy and similar functions, which have an 
extra parameter n that specifies the maximum number of characters copied. 
But, C++ programmers have access to a better solution: use C++ string 
objects. They're safe from these kinds of problems (as you can see from 
these examples).
*/

