0

This is a bizarre error that I have never seen before, and do not know how to fix it. The crash occurs on

na = m

Here is the relevant code. The line in question is marked with *:

In Main:

#include <cstdlib>
#include <iostream>
#include "stu.h"
#include <string>
#include <iomanip>

using namespace std;

int main(int argc, char *argv[])
{   
    stu stu;
    int score[2];

    std::string name;
    std::cout <<"enter name:";
    std::cin >> name;
     //THIS IS AN EDIT IN  AFTER SEEING THAT A IMPORTANT ERROR POINT WAS NOT SHOWN TO THE FIRST COUPLE REPLY 
       ************************************************************
     //THIS IS CAUSING THE PROBLEM WHEN I COMMENT IT OUT THE PROGRAM WORKS 
     std::cout << "enter score 1:";
     std::cin >> score[0];
     std::cout << "enter score 2:";
     std::cin >> score[2];
     std::cout << "enter score 3:";
     std::cin >> score[3];
      *************************************************************
    stu.setname( name );

    // ...
}

In stu.ccp:

void stu::setname(std::string m)
{
    std::cout <<"1";//<--to find where the code was crashing 

    na = m; // *** the crash

    std::cout <<"1";
}

In stu.hpp:

class stu
#include <string>
{
public:
    stu();
    void setname(std::string);
    std::string getname();
    void settest(int, int,int);
    void display();

private:
    std::string na;

    int score[2];   
};

4 Answers4

1

When you define int score[2] you get an array of 2 int and the valid array indices are 0..1.

Your later code writes past the end of the array and trashes whatever follows it in memory, in this case the string object name.

std::cout << "enter score 1:";
std::cin >> score[0];
std::cout << "enter score 2:";
std::cin >> score[2];
std::cout << "enter score 3:";
std::cin >> score[3];

The last two array references are incorrect.

Blastfurnace
  • 18,411
  • 56
  • 55
  • 70
1

You allocated enough space for two integers in an array, having valid indices 0 and 1.

 int score[2];

Then you tried to read more elements than that

 std::cin >> score[2];
 std::cout << "enter score 3:";
 std::cin >> score[3];

This is undefined behavior and anything is allowed to happen, including your entire computer disappearing in a fireball. In your case, it overwrote the memory next to the array, which was your string variable. Making a copy of a corrupted string can easily crash the program.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
0

I've tried your code, it compiles and also runs with no problem.

Except for what you've provided I've just defined also the constructor, moved #include <string> before class stu in stu.h and removed that std::cout << "1".

ssell
  • 6,429
  • 2
  • 34
  • 49
DrM
  • 154
  • 7
0
int score [2]

will only have score[0] and score [1] spots for values. use Try

   int score[3]

Then store your values in

 score[0];
 score[1];
 score[2];
user758114
  • 354
  • 5
  • 22