segmentation fault with single integer - c++

So I'm making a class which is just an easy way to manipulate an array of a different class and perform a few operations on it (fractions if you wanted to know)
NOTE: this is my homework but I don't think this violates any kind of rule because I'm not asking how to do it, but what the issue is. However, if you would have any sort of moral dilemma with this, I'm just letting you know now.
The function uses a for loop to go through an array - but not out of array bounds, because I changed the code to not even use the array
for (int i = first - 1; i < last - 1; i++) cout << i;
and I still get a seg fault when i is 4.
In the scope of the function call, i is not a variable.
The line of output from this call is
0123
Segmentation fault
so for all I know, changing i to 4 causes the error.
Member data in the class is
private:
int size;
Fraction arr[20];
the function in the header is
Fraction Product(int first, int last) const;
and the code that uses it preceding the error is this (from Bob Myers FSU CS Dept)
http://www.cs.fsu.edu/~myers/cop3330/hw/hw4files/main.cpp
#include <iostream>
#include "flist.h"
using namespace std;
int main()
{
int start;
Fraction entry;
FList a;
cout << "Welcome!\n";
cout << a;
cout << "How many numbers to start with (1 - 20)? ";
cin >> start;
cout << "Please input the " << start << " starting fractions\n";
for (int i = 0; i < start; i++)
{
cout << "Fraction #" << (i+1) << ": ";
entry.Input();
a.Insert(entry);
}
cout << "\nHere's the list:\n" << a;
cout << "Size of list = " << a.Size() << '\n';
cout << "Sum of items in list = " << a.Sum();
cout << "\nProduct of first 5 fractions in list = " << a.Product(1,5);
I don't know much about computer organization and what's really going on behind memory allocation but I don't see how an integer can change value without changing the amount of bytes used and then become invalid memory, so I would really appreciate someone who can say I'm approaching this the wrong way.

Related

Two Consecutive for loop in C++, Second loop is not working

Objective: I have two arrays. 1st Array is: evenList and the 2nd is: oddList. I want to print the even and odd numbers between the given ranges in this format.
This is my code,
cout << "\nEven numbers between " << lowerLimit << " to " << upperLimit << ": ";
for(int i; i < evenList.size(); i++){
cout << evenList[i] << " ";
}
cout << "\n\nOdd numbers between " << lowerLimit << " to " << upperLimit << ": ";
for(int j; j < oddList.size(); j++){
cout << oddList[j] << " ";
}
the first for loop prints the desired output but the second loop don't show the odd numbers. Here is the output:
I've read some of contents about for loops already but I just can't get the answer. If someone facing the same question or problem and got the answer, please share. I will really appreciate it.
You're not initializing your iterators. int i; should be int i = 0;, and likewise for int j. As it is now, this is undefined behavior. It's just chance that it worked the first time and not the second time, it might as well work both times, not work at all, crash right off the bat or do something entirely different.
Does your compiler emit a warning for this code? Ideally, it should say something like "uninitialized local variable 'i' used". Always listen to compiler warnings, they can help point out some common mistakes. If your compiler issues no warning here, try to see if you can configure it to be more strict with warnings.
I have two point that is leading you to your undesired output.
It is always good to initialize a variable. In most cases, it might lead you to segmentation fault. In the above code, you've not initialized the variables in the for loop.
I have not used C++ but I suppose that you're using array, evenList and oddList. And you're using a condition j<oddList.size(). The only way this condition can go wrong is if doesn't have any element in oddList array. Check whether you have any elements in those array.
Try to use FOR EACH LOOP to prevent the variable initialization confusion.
for(string s : eventList){ cout << s << endl; }
and same for the second loop. Hope this time it works
You can also use а Range-based for loop
cout<<"\nEven numbers between " << lowerLimit << " to " << upperLimit << ": ";
for (const auto &e: evenList)
{
cout << e << " ";
}
cout << "\n\nOdd numbers between " << lowerLimit << " to " << upperLimit << ": ";
for (const auto &o: oddList)
{
cout << o << " ";
}

Space at the end of first cout statement shows at the beginning of second cout

There's some cout statement but the space at the end of the first cout statement shows up at the beginning of second cout statement. Here's the code:
#include <iostream>
int main()
{
using namespace std;
cout << "Enter the starting countdown value: ";
int limit;
cin >> limit;
int i;
for (int i = limit; i; i--)
{
cout << "i = " << i << "\n";
}
cout << "Done now that i = " << i << "\n";
return 0;
}
And here's the output:
There is no space there, at least one that can be reproduced, as shown in the screenshot. As #LightnessRacesInOrbit commented though: Flushing periods are implementation-dependent so we can expect reproducibility to vary.
The real problem of your code:
You have two variables named i: one outside, one inside the for loop.
As a result, the for loop uses the i declared in it, and behaves as desired.
However, here:
cout << "Done now that i = " << i << "\n";
you are printing an uninitialized variable i.
A strong hint for you to have found the problem would be to read the warnings issued by the compiler, as shown below:
Also notice the garbage value of i being printed when you are done, which is the main indication that something is wrong in your code.
An easy fix would be to change this:
for (int i = limit; i; i--)
to this:
for (i = limit; i; i--)
and then the last line of your output would be this:
Done now that i = 0

Strange result of displaying array using increment/decrement operator in C++

#include <iostream>
using namespace std;
int main()
{
double donation[10];
int index = 0;
cout.setf(ios::fixed);
cout << "Enter sum of money for donating: ";
while (index < 10 && cin >> donation[index])
{
cout << "donation #" << 1 + index++ << ": " << donation[index] << endl;
}
return 0;
}
Result
That code couldn't display right value of donation...
I could check the mistake is '1 + index++', but I don't know why did.
Why my code using '1 + index++' has a difference with code when I use 'index++' in the next line.
Keep to the idiomatic way instead of trying to understand stranger constructions and also mixing increments with function/operator parameters should be avoided (see sequence points):
for (int index = 0; index < 10; ++index)
{
if (! std::cin >> donation[index])
break;
std::cout << "donation #" << (1 + index) << ": " << donation[index] << std::endl;
}
This should do what is expected and should be understood with some knowledge of C++. It runs at most 10 times, tries to fill input to the array and displays when the input works or stops when the input fails. The only issue would be better validation of the user input.

Why arrays do not print whole table?

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int d,m;
int districts=3;
int months = 12;
double sales[districts][months];
for (d=0 ; d < districts; d++)
{
for(m=0; m< months; m++)
{
cout << "Enter sales for District " << d+1 << ":" << " and Month " << m+1 << ": ";
cin >> sales[districts][months];
}
}
cout << "\n\n\n";
cout << setw(40) << "Months\n";
cout << setw(26) << "1 2 3 4 5 6 7 8 9 10 11 12\n";
for (d=0; d < districts ; d++)
{
cout << "District " << d+1;
for(m=0; m< months; m++)
{
cout << ": " << sales[districts][months];
}
}
return 0;
}
This code after running takes only two input values from user and after that a window appear displaying message a problem caused the program to stop working correctly.
There are no compilation errors and I am unable to find the problem. Is there anyone who can help?
You use variables d and m as counter-variables for your loops, but inside the loops you use the maximum value for both of them (districts and months) instead of d and m.
Change this: cin >> sales[districts][months]; to this: cin >> sales[d][m];
Also, this: cout << ": " << sales[districts][months]; to this: cout << ": " << sales[d][m];.
The term sales[districts][months] refers to a particular element sales[3][12], which also happens to be out of bounds for the 2-d array.
The reading loop is repeatedly reading a value to sales[districts][months], i.e. to sales[3][12], which - since array indexing starts at zero in all dimensions, doesn't exist. That gives undefined behaviour.
The output loops are repeatedly outputting the same value, which also gives undefined behaviour.
A common symptom (but not the only possible one) of undefined behaviour is abnormal program termination - and you are seeing an example of that.
There is also the wrinkle that
int districts=3;
int months = 12;
double sales[districts][months];
involves a variable length array (VLA) which is a feature of C (from the 1999 C standard or later) but is not valid C++. If that construct works for you, your compiler supports a non-standard extension.

Trouble with dynamic arrays and finding the sum of values

So as I explained in the title i'm having trouble trying to get the sum of an array. I've just now learned how to create dynamic arrays and I did some searching on how to calculate the sum. I don't believe I fully understand what is going on to calculate the sum.
// Final Grade Calculator
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main(){
double minor, quiz, major;
int minorG, quizG, majorG;
minorG = 0;
cout << "Final Grade Calculator" << endl;
cout << "Input minor grade weight percent." << endl;
cin >>minor;
cout << "Input quiz grade weight percent." << endl;
cin >>quiz;
cout << "Input major grade weight percent." << endl;
cin >>major;
// Three grade categories
minor = minor/100;
quiz = quiz/100;
major = major/100;
for(int i = 1; i <=10; i++){
cout << "Input a minor grade. (Max=10)" << endl;
cin >>minorG;
int *minorGA = new int[minorG];
minorG+= minorGA[minorG];
cout << "Currently: " << i << " Grade(s)." <<endl;
}
cout << "Minor Sum: " << minorG << endl;
return 0;
}
This is what I have so far and the trouble I am having is within the for loop which is where my array is and where I am trying to get the sum of it. When I compile and run I get a sum of 138,427. Any help would be greatly appreciated!
I think you're over-complicating things with dynamic arrays. I'll explain what you're doing, and try to provide help for what I think you're trying to do.
In your code int* minorGA = new int[minorG]; you are allocating memory for minorG amount of ints. There are two problems here:
You are accessing an element outside of the memory you allocated. When you allocate 10 elements, you can access elements 0-9. Trying to access 10 is undefined behaviour (you are trying to access parts of memory that could contain anything).
The values stored in this array are just whatever is in memory, so when you are attempting to increment minorG by the amount of one of these, it's just whatever is in memory at the time.
A separate problem is that you are not deallocating the memory, but some might argue that it isn't really a problem.
You should just be able to have the following to perform what I think you're trying to do:
for (int i = 0; i < 10; ++i)
{
int inputtedNumber = 0;
cout << "Enter a number" << endl;
cin >> inputtedNumber;
// add that number to some tally:
finalTally += inputtedNumber;
}
Or if you are trying to store the elements in an array, you can use the following:
const int maxElements = 10;
int grades[maxElements] = {}; // this will construct all elements with 0. Without this, the elements may contain any number.
for (int i = 0; i < maxElements; ++i)
{
int inputtedNumber = 0;
cout << "Enter a number" << endl;
cin >> inputtedNumber;
// Store the number
grades[i] = inputtedNumber;
}
In saying that, it will be better to use std::vector (knows its size, handles memory for you, can grow):
std::vector<int> grades;
// Allow the user to enter as many numbers as they'd like
for (;;)
{
int input = 0;
cout << "Enter a number" endl;
cin >> input;
// Store the number. Will continue to grow
grades.push_back(input);
}