Stack around the variable "name" was corrupted

Never seen this error before in my life. I believe, after some research, it may have to do with array overflow, however, I have used array length MUCH smaller than the max (which I've set at 50) and it still gives me the error. In addition, I've run it in C++ Shell online and it gives me no problems or errors. VS 2015, however, is where this error is being given. Because it is more rigorous of an IDE, I am assuming that's why it knows something is wrong...

Here is my code (it's rather simple):

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <iomanip>
using namespace std;

void load(char *, float &, int &, float &);
void calc(float &, float &, float &, float, int, float);

void load(char *name, float &pp, int &sh, float &cp)
{
	cout << "Enter the name of the stock: ";
	cin.getline(name, 50);
	cout << "Enter purchase price: ";
	cin >> pp;
	cout << "Enter number of shares: ";
	cin >> sh;
	cout << "Enter current price: ";
	cin >> cp;
	cout << endl;
}

void calc(float &ic, float &cv, float &pr, float pp, int sh, float cp) //anything being returned has to be returned with a reference "&"
{
	//run calculations
	ic = pp * sh;
	cv = cp * sh;
	pr = cv - ic;

	//print out results of said calculations in proper money format
	cout << "Initial Cost: " << setprecision(2) << showpoint << fixed << '$' << ic << endl;
	cout << "Current Value: " << setprecision(2) << showpoint << fixed << '$' << cv << endl;
	cout << "Profit: " << setprecision(2) << showpoint << fixed << '$' << pr << endl;
}

int main()
{
	char name;
	float pp;
	int sh;
	float cp;
	float ic;
	float cv;
	float pr;

	load(&name, pp, sh, cp); //notice call by pointer 
	calc(ic, cv, pr, pp, sh, cp);

	return 0;

	system("PAUSE");
}
Last edited on
1
2
3
4
void load(char *name, float &pp, int &sh, float &cp)
{
	cout << "Enter the name of the stock: ";
	cin.getline(name, 50);

The variable you passed in for the parameter name, can only store a single character, not 50. You'll need to dynamically allocate memory for name in main() and pass that pointer to load(). Better yet, use std::string.
line 36; that's not a char pointer or a char array, so it can only take a single char... you're basically trying to write data to an array that isn't there, so it's causing your errors.

char name[51];
...
load(name, pp, sh, cp);

Edit: darn, lost by a minute...
Last edited on
damn...i can't believe i didn't see that. thanks so much guys.
Topic archived. No new replies allowed.