Something called Stack Overflow

So I'm a high school student learning C++. My project is to make a basic-terminal based inventory system for the Chemistry lab. Since we haven't reached Data Handling I was trying a prototype for the code. In DevC++ the compiled code
just flat out crashed the terminal prompt and in Visual Studio It opened another tab showed a bunch of code I couldn't understand and gave me something called a "Stack Overflow". I'm posting the code here. Please help me.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include "stdafx.h" //removed this in DevC++
#include<iostream>
using namespace std;
class Chem_basinfo {
public:
	char name[100], chem_formula[40];
	class exp_no {
	public:
		char exp[100];
	}exp_number[100];
};
class stock :public Chem_basinfo {
	char no_containers[100];
	int production_date, expiry_date;
};
int main()
{
	stock chem[1000];
	cout << "Basic Info";
	cout << "Enter Chemical name";
	cin >> chem[1].name;
	cout << chem[1].name;
	system("pause");
	return 0;
}

programs us a stack structure to store local variables and function calls and internal workings. If you exceed its capacity, which takes a lot of data, you can get a stack overflow. I don't see why here, yet, and I have to run, but you have something that is too large to be static data.
You have 1000 stock objects in stack.

One stock object contains:
2 int
100 char (no_containers)
100 char (name)
40 char (chem_formula)
100 exp_no, but each exp_no has 100 char, i.e. 10'000 char

In short: 10'240 char + 2 int

The array of thousand thus requires stack memory for:
10'240'000 char + 2'000 int


An array of char is more difficult to keep safe. It has fixed size, but user input might be more or less than that. std::string is easier and safer, and does not store the text in stack (except as optimization that you don't have to worry about).

std::vector is a more generic dynamic array type that also stores data outside of stack.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include<iostream>
#include<vector>
#include<string>

using std::string;
using std::vector;
using std::cout;

struct Chem_basinfo {
  string name;
  string chem_formula;
  vector<string> exp_number; // empty vector, 0 elements
};

struct stock : public Chem_basinfo {
  string no_containers;
  int production_date;
  int expiry_date;
};

int main()
{
  vector<stock> chem( 1000 ); // 1000 elements
  cout << "Basic Info";
  cout << "Enter Chemical name";
  std::cin >> chem[0].name; // indexing starts from 0
  cout << chem[0].name;
  return 0;
}
Topic archived. No new replies allowed.