Program crashes sometimes when dynamically allocating memory [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am learning about pointers and dynamically allocating memory. So my question I guess is more of a technical issue. Whenever it seems I use the 'new' keyword to allocate memory for whatever I am doing, my program will sometimes crash. Sometimes not.
#include <iostream>
#include <iomanip>
#include <cstdlib> //I added this header file to get the NULL, this is not originally from the book
using namespace std;
int main(){
double *salesArry = NULL;
double total = 0.0, average;
int numDays, count;
cout << "How many days of sales figured do you wish to process ";
cin >> numDays;
salesArry = new double[numDays];
cout << "Enter the sales figures below.\n";
for(count = 0; count < numDays; count++){
cout << "Day " << (count + 1) << ": ";
cin >> salesArry[count];
}
for(count = 0; count < numDays; count++){
total += salesArry[count];
}
average = total/numDays;
cout << fixed << showpoint << setprecision(2);
cout << "\n\nTotal Sales: $" << total << endl;
cout << "\n\nAverage Sales: $" << average << endl;
delete [] salesArry;
salesArry = NULL;
return 0;
}
Full disclaimer: I am a student, this is NOT homework. I posted a book example. I copied it word for word and still my program crashes. My only reason for posting code is someone will proably ask "Can we see the code". Now the project I was working on is doing the same thing (crashes) so I doubt that both the book and I are wrong so that is why I'm guessing its a technical issue. The IDE I am using is Dev C++ and its the default compiler.
This is from Tony Gaddis's book "Starting Out with C++" Chapter 9, page 524

new double(numDays);
Whoops! When you transcribed the book, you made a typographical error. (I can confirm that the 8th Edition, which you said you're using, does not make this mistake (figure 9-14, et al.).
To dynamically allocate an array, you must use square brackets, otherwise you're just initialising one dynamically-allocated double with the value numDays.
new double[numDays];

salesArry = new double(numDays);
That line doesn't create an array of numDays doubles, it allocates a single double and initializes it to numDays.
To create an array, you would use:
salesArry = new double[numDays];
In C++, however, it is preferable to use std::vector instead of dynamically allocating arrays by hand:
std::vector<double> salesArray (numDays);

Related

Why is the int function acting strange when I set it to 500? c++ [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 11 months ago.
Improve this question
I am trying to set a int to 500, but random numbers such as 22067 come out.
I am trying to make a simple gambling game. Currently, what I'm doing is that I set int gambledMoney = 500; But when I ask to print the 500, it does work but instead it prints 22067. Here is my code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
//introduction
cout << "Why hello human!\nWelcome to this gambling game where you... gamble!\nTo explain how to play here are the steps:\n\n";
//instructuions
cout << "You always start with $2000.\nAt the very beginning of each new round, you will be given choices on the amount of money you will gamble.\n";
cout << "Then you will gamble against an AI.\nIf you win, you gain the amount that the AI gambled...\nBut if you lose, you lose the money that you gambled.\n";
cout << "If you reach $500, you lose. Same goes with the AI.\n";
//game start
cout << "\nNow lets start!\n";
//gamble amount
string gambleChoice;
int gambledMoney;
cout << "\nHow much would you like to gamble?";
cout << "\n A) $500\n B) $750\n C) $1000\n D) $1250\n E) $1500\n F) $1750\n G) $2000\n\n";
//amount chosen
cin >> gambleChoice;
if (gambleChoice == "a")
{
int gambledMoney = 500;
}
cout << "\nYou have gambled $" << gambledMoney << "!" << endl;
return 0;
}
Does anyone know why it is not putting 500?
You are declaring two different variables with the name gambledMoney in different scopes, so that one variable "shadows" the other variable with the same name.
The line
int gambledMoney = 500;
will create a new variable with that name, and set it to 500. It won't change the value of the existing variable to 500.
You probably want to change that line to the following:
gambledMoney = 500;
That way, it will change the value of the existing variable, instead of creating a new one.
If you are using the compilers gcc or clang, I recommend that you compile with the -Wshadow command-line option. That way, the compiler will warn you when you create two variables of the same name, so that one shadows the other.
That is not the only compiler warning that I recommend enabling, though. You may want to read this for further information:
Why should I always enable compiler warnings?

Why the loop only run one time? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I tried to do a phone Sys and I used a while loop in the main{}. I don't know why it only runs one time, it suppose to run infinite time unless I give it command to stop.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void record(string name, int phoneNum, int count);
// main
int main() {
cout << " Welcome to use the Phone Contact Systerm " << endl;
string name;
int phoneNum;
int count = 0;
string signToStop;
cout << " Please enter name and phone number " << endl;
while ( cin >> name >> phoneNum){
cout << " If you want to start the program, enter start " << endl;
cout << " If you want to quit the program, enter quit " << endl;
cin >> signToStop;
if (signToStop == "start"){
record(name, phoneNum, count);
}
else if ( signToStop == "quit" ){
break;
}
count++;
}
}
// record all name info into Name set and record all phone numbers into PhoneNum set
void record(string name, int phoneNum, int count){
string Name[] = {};
int PhoneNum[] = {};
Name[count] = {name};
PhoneNum[count] = {phoneNum};
// now start to record all the info into .txt document
ofstream phoneFile;
phoneFile.open("contact.txt");
phoneFile << name << " " << phoneNum << endl;
}
The result is:
Welcome to use the Phone Contact Systerm
Please enter name and phone number
Molly 5307659229
Process finished with exit code 0
Maybe try ulong int for the phone number, it might be too long. Also I might add that I am a bit confused, as your function record() has a 3rd argument that has no default argument. Your problem might lie there too. As without a default you need to put the argument in when it is used.
As spectras said, a phone number is not really an integer, and so it's not a "number" in the programming (or even mathematical) sense.
It's more like a sequence of digits; that is, a string.
You have two problems when you try to interpret it as an int:
Your int type is too small for the value (this is what's causing your loop to end)
Leading zeroes are not meaningful (at best, it's used to flip into octal mode, which is not what you wanted).
I'd instead read it as a string. You can still validate it later, like "is every character a digit?".

Simple C++ calculation giving odd outputs [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I'm working on a C++ program to calculate a speeding ticket fine for different speeds.
"The speeding ticket fine policy in (City) is $50 plus $5 for each mph over the limit plus a penalty of $250 for any speed over 85 mph. Write a program that accepts a speed limit and a clocked speed and either prints a message indicating the speed was legal or prints the amount of the fine, if the speed is illegal.In the program, you also need to display whether the number of miles over the speed limit, and if he/she is driving over 85 mph."
Here's my code:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double speedlimit,clockedspeed,speeddifference,fineunder85,fineover85;
speeddifference = clockedspeed-speedlimit;
fineunder85 = (speeddifference*5)+50;
fineover85 = (speeddifference*5)+300;
cout<<"Enter the speed limit: "<<endl;
cin>>speedlimit;
cout<<"Enter the clocked speed: "<<endl;
cin>>clockedspeed;
if ((clockedspeed > speedlimit) && (clockedspeed > 85))
{
cout<<"The clocked speed is: Illegal"<<endl;
cout<<"Miles over the speed limit: "<<setprecision(2)<<speeddifference<<endl;
cout<<"Driving over 85 mph: Yes"<<endl;
cout<<"The fine is: $"<<setprecision(2)<<fineover85<<endl;
}
else {
cout<<"The clocked speed is: Illegal"<<endl;
cout<<"Miles over the speed limit: "<<setprecision(2)<<speeddifference<<endl;
cout<<"Driving over 85 mph: No"<<endl;
cout<<"The fine is: $"<<setprecision(2)<<fineunder85<<endl;
}
}
I'm getting weird outputs for (speeddifference) like "-7e-310" and the fine isn't adding the additional penalty ($5/mile over the limit) but is only outputting "$50" or "$300".
Just looking for help, I've searched everywhere and I've come up short.
ty all
You're calculating the speed difference and fines before you even input the numbers! Remember that the program runs line by line (without functions, classes, etc. just procedural programming). Furthermore, you declare the variables without defining them with a set value which is why you are getting random values.
Move the:
speeddifference = clockedspeed-speedlimit;
fineunder85 = (speeddifference*5)+50;
fineover85 = (speeddifference*5)+300;
to after you receive input.
Edit:
There seems to be numerous other errors and I've tried my best effort to fix all of them. Here's a reworked version.
#include <iostream>
int main()
{
double fine = 0;
double speed_limit;
double clocked_speed;
std::string over_85 = "no";
std::cout << "Speed limit:\n";
std::cin >> speed_limit;
std::cout << "Clocked speed:\n";
std::cin >> clocked_speed;
double speed_difference = clocked_speed - speed_limit;
fine += 50 + speed_difference * 5;
if (clocked_speed > 85) {
fine += 250;
over_85 = "yes";
}
if (clocked_speed <= speed_limit) {
std::cout << "\nLegal\n";
}
else {
std::cout << "\nIllegal\n"
<< "Miles over: " << speed_difference << '\n'
<< "Over 85mph: " << over_85 << '\n'
<< "Fine: $" << fine << '\n';
}
}
Changes:
Set a variable string over_85; to remove need of complicated if statement.
Remove need for two different fines and instead have one fine with an if statement to add the $250 fine if necessary.

From the user's input total the odd and even numbers. input numbers in between 0 to 99 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
#include <iostream>
using namespace std;
int main()
{
int i,t,x[20], even, odd, prime;
cout << "Enter 20 integer numbers from 0 to 99: "<<endl;
for (i=1;i<=20;i++)
{
cout << "Input " << i <<":";
cin >> x[i];
}
cout << "\nPrime numbers are: " << endl ;
prime=1;
for (i=2; i<=20 ; i++)
{
for(t=2;t<x[i];t++)
{
if(x[i]%t==0)
{
prime=0;
}
}
if(prime==1)
{
cout << x[i] << endl;
}
prime=1;
}
for(i=1; i<=20; i++) // this is where i have problem.
{
if(x[i]% 2 == 0)
{
even++;
}
else
{
odd++;
}
}
cout << "Number of odd numbers: " << odd << "\n";
cout << "Number of even numbers: " << even << "\n";
return 0 ;
}
When i compile it shows even (40) and odd (10) for input of 0 till 19. Where it should show even 10(including the 0) and odd (10). Im not sure where am i doing it wrongly. I hope someone can help me improve the code.
Variables even and odd are never set to a known value, so you are not formally allowed to read from them. Doing so invokes that most infamous Standardese concept: undefined behaviour. So the values of these variables could be right or could be wrong; the variables and all code trying to read them could be optimised entirely out of your program; or anything can happen. You cannot rely on these variables doing anything right. All attempts to read them make your program ill-formed, so now it can do anything, including things you would never have imagined.
You should search for the abundant background info about these concepts, but I like to think I made a fairly decent summary here: https://stackoverflow.com/a/38150162/2757035
Also, as Thomas points out in the comments, you appear not to understand how array indexing works: Indexes are 0-based. So, int i[20] declares 20 elements numbered from 0 to 19. You try to access index 20, which is not part of the array and hence is more undefined behaviour.

Professors example of `new` in C++ will not work on my machine [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
This is the professor's code:
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include<string>
#include <new>
int main()
{
char *p;
int index = 8;
cout << "Input how many characters:";
cin >> index;
p = new char [index + 1];
cin >> p;
cout << "p is: " << p;
delete [] p;
p = NULL;
return 0;
}
After I ANSWER "how many characters" statement with a number the program stops.
Anyone knows why?
First you have
cin >> index;
where you have to input the number of characters.
Then you have
cin >> p;
where you have to input some characters - but no more than the number you gave before. Are you doing that? It might be helpful to give another prompt:
cout << "Input up to " << index << " characters:";
cin >> p;
I hope your professor is going to follow this up with an explanation of buffer overruns, input validation, exception safety, and how to use std::string to avoid faffing around with manual allocation. Otherwise, you're being taught some very bad habits.