C++ program is crashing for some unknown reason - c++

I started learning C++ recently, and thought I would test my mettle with Project Euler problems. I solved the first two, but I am stuck on the third. It is compiling correctly without any errors, but it is crashing as soon as it is executed. I tried removing the nested for loops to isolate the problem, and it still crashed.
#include<iostream>
#include<math.h>
int main()
{
float quot;
int num = 0;
int array[100];
float next;
for(int i = 0; i < 100; i++)
{
for (int j = 0; j < 100; j++)
{
if((i % j) == 0)
{
quot=j/i;
num=num+1;
}
if (num=2)
{
array[i]=i;
}
}
}
for (int i = 0; i < 100; i++)
{
if((13195 % i) == 0)
{
std::cout << i;
}
}
}

In if((i%j)==0) if i and j are zero, your next line is dividing i and j. This is division by zero.

Related

What is truncation in C++?

I'm having my code compiled successfully, in most of the cases it works perfectly well, but on some cases containing long and great numbers of inputs to my array the result turns into something strange and minus, and the compiler shows 'truncated' in front of the last input. What is wrong with it? When does this happen?
Here's my code:
#include<iostream>
using namespace std;
int main()
{
int n, index, max, deletion;
cin>>n;
int ar[n];
long long freq[100]={0};
for (int i = 0; i < n; i++)
{
cin>>ar[i];
}
for (int i = 0; i < n; i++)
{
index=ar[i];
freq[index]++;
}
max=freq[0];
for (int i = 0; i < 101; i++)
{
if(max < freq[i])
{
max=freq[i];
}
}
deletion=n-max;
cout<<deletion<<endl;
return 0;
}

Finding evens in an array

I'm writing a program that is made of a function that takes in a 2d array, c0unts the evens in the array and returns the amount of evens in that array. The function isn't returning the value that i intend it to, which is 6. Sometimes I get 0, sometimes I get a number like 2147483646.
#include <iostream>
#include <array>
using namespace std;
const int MaxNumOfRows = 3;
const int MaxNumOfColumns = 2;
int Even(int A[MaxNumOfRows][MaxNumOfColumns], int length, int width)
{
int NumnberOfEvens = 0;
int i;
int j;
for (i = 0; i < length; length++)
{
for (j = 0; j < width; width++)
{
if (A[i][j] % 2 == 0)
{
NumnberOfEvens++;
}
}
}
return NumnberOfEvens;
}
int main()
{
//int output = 0;
int A[MaxNumOfRows][MaxNumOfColumns] =
{
{2,2},{2,4},{2,2}
};
Even(A, MaxNumOfRows, MaxNumOfColumns);
//output = Even(A, MaxNumOfRows, MaxNumOfColumns);
cout << Even(A, MaxNumOfRows, MaxNumOfColumns) << endl;
system("pause");
return 0;
}
Check those for loops, I imagine you want to be incrementing the variables ++i and ++j rather than width++ and length++.
With an example this trivial, I imagine stepping through the executing code and finding the problem in a debugger would be pretty straightforward...are you writing this using an IDE with a debugger?
You are not applying increment on loop variables ('i' and 'j') here. 'length' and 'width' are increasing (due to length++, width++) whereas 'i' and 'j' are not. So, loop won't stop and thus the garbage values.
for (i = 0; i < length; length++)
{
for (j = 0; j < width; width++)
{
if (A[i][j] % 2 == 0)
{
NumnberOfEvens++;
}
}
}
This must work.
for (i = 0; i < length; i++)
{
for (j = 0; j < width; j++)
{
if (A[i][j] % 2 == 0)
{
NumnberOfEvens++;
}
}
}

c++ heap corruption dectected

I am getting an heap corruption error when running a code from my textbook.However, when I run it through an online compiler, it works. I am using visual studio 2013. I assume the code is correct; Is it might be something wrong with my visual studio? Any help will be appreciated, thanks!
#include <iostream>
#include<cstdlib>
#include<ctime>
#include<iomanip>
using namespace std;
int main() {
// your code goes here
srand(time(0));
int* counts[10];
// Allocate the rows
for (int i = 0; i < 10; i++)
{
counts[i] = new int[i + 1];
for (int j = 0; j <= 1; j++)
{
counts[i][j] = 0;
}
}
const int RUNS = 1000;
// Simulate 1,000 balls
for (int run = 0; run < RUNS; run++)
{
// Add a ball to the top
counts[0][0]++;
// Have the ball run to the bottom
int j = 0;
for (int i = 1; i < 10; i++)
{
int r = rand() % 2;
// If r is even, move down,
// otherwise to the right
if (r == 1)
{
j++;
}
counts[i][j]++;
}
}
// Print all counts
for (int i = 0; i < 10; i++)
{
for (int j = 0; j <= i; j++)
{
cout << setw(4) << counts[i][j];
}
cout << endl;
}
// Deallocate the rows
for (int i = 0; i < 10; i++)
{
delete[] counts[i];
}
return 0;
}
Here
for (int i = 0; i < 10; i++)
{
counts[i] = new int[i + 1];
for (int j = 0; j <= 1; j++)
{
counts[i][j] = 0;
}
}
for counts[0] you allocate memory for only one int (counts[0] = new int[0+1]). In inner loop you try to access counts[0][1]. Therefore, you go beyond the boundaries of the array and get heap corruption.

SIGSEGV(signal 11) 'segmentation fault' in FCTRL2 codechef

I am facing SIGSEGV error on submitting solution for codechef small factorial problem code FCTRL2 though the code works fine on ideone
coding language C++ 4.3.2
Example
Sample input:
4
1
2
5
3
Sample output:
1
2
120
6
#include <iostream>
using namespace std;
void fact(int n) {
int m = 1, a[200];
for (int j = 0; j < 200; j++) {
a[j] = 0;
}
a[0] = 1;
for (int i = 1; i <= n; i++) {
int temp = 0;
for (int j = 0; j < m; j++) {
a[j] = (a[j] * i) + temp;
temp = a[j] / 10;
a[j] %= 10;
if (temp > 0) {
m++;
}
}
}
if (a[m - 1] == 0) {
m -= 1;
}
for (int l = m - 1; l >= 0; l--) {
cout << a[l];
}
}
int main() {
int i;
cin >> i;
while (i--) {
int n;
cin >> n;
fact(n);
cout << endl;
}
return 0;
}
Caveat I'm not going to just fix up your code for you straight up, but I will highlight where it's going wrong and why you get the seg fault.
Your problem is with your implementation of how you're trying to handle the digit by digit multiplication - specifically with what happens to your m value. Test it out by outputting m each time it's incremented - you'll find it's incrementing more often than you intend. You're right to realise you need to use an approach to get to 158 digits and your basic concept could be made to work.
The first clue is by testing with n = 6 when you get a leading 0 that you shouldn't even though you try to get rid of that problem with the if block that contains m-=1
Try with n = 25 and you will see a lot of leading zeros.
Any value greater than this will fail with a Segmentation error. The Seg fault is because, with this error, you try to set values of the array a beyond the max index (as m gets greater than 200)
N.B. Your assertion that the code works on Ideone.com is only true up to a point - it will fail with n > 25.
(Erased code computing a factorial using int)
The problem in your code is that you increment m each time temp is not 0 for each digit multiplication. You may then get a SIGSEGV when computing big factorials because m becomes too big. You probably saw it because 0 shows up in front of your result. I guess this is why you added the
if (a[m - 1] == 0) {
m -= 1;
}
You should only increment m when the inside loop is finished and term is not null. Once fixed you can get rid of the above code.
void fact(int n) {
int m = 1, a[200];
for (int j = 0; j < 200; j++) {
a[j] = 0;
}
a[0] = 1;
for (int i = 1; i <= n; i++) {
int temp = 0;
for (int j = 0; j < m; j++) {
a[j] = (a[j] * i) + temp;
temp = a[j] / 10;
a[j] %= 10;
}
// if (temp > 0) {
// a[m++] = temp;
// }
while (temp > 0)
{
a[m++] = temp%10;
temp /= 10;
}
}
for (int l = m - 1; l >= 0; l--) {
cout << a[l];
}
}

Sieve of Eratosthenes implementation

I am trying to implement algorithm for Sieve of Eratosthenes but I don't know why this program crashes for larger programs. Initially I was using vector but now I am implementing this using dynamic memory allocation.
#include<iostream>
#include<cmath>
#include<cstdlib>
using namespace std;
unsigned isqrt(unsigned value) {
return static_cast<unsigned>(sqrt(static_cast<float>(value)));
}
int main()
{
int t;
cin >> t;
long long * N;
long long * M;
long long n, m;
N = new long long[t];
M = new long long[t];
for(int i = 0; i < t ; i++){
cin >> M[i] >> N[i];
}
for(int i = 0; i < t ; i++){
n = N[i];
m = M[i];
bool * A;
A = new bool[n];
if(A == 0)
{
cout << "Memory cannot be allocated";
return 0;
}
for(int i=0;i < n;i++){
A[i]=true;
}
A[0] = false;
A[1] = false;
unsigned sqrt = isqrt(n);
for(int i = 2; i <= sqrt; i++)
{
if(A[i] == true){
for(int j = i*i; j <= n; j = j + i)
{
A[j] = false;
}
}
}
for(int i = m;i < n;i++)
{
if(A[i] == true )
cout << i << "\n";
}
delete[] A;
}
delete[] M;
delete[] N;
return 0;
}
The program crashes for larger values of n and m (~10^16). Kindly help me out.
for(int j = i*i; j <= n; j = j + i)
^^
If j == n then A[j] = false will assign to an element past the end of the array. The test should be j < n.
If you're going to write a sieve of Eratosthenes in C++, how about if you actually use C++, not try to treat it as some demented cross between C and assembly language.
#include <vector>
#include <iostream>
unsigned long primes = 0;
int main() {
int number = 10000000;
std::vector<bool> sieve(number,false);
sieve[0] = sieve[1] = true;
for(int i = 2; i<number; i++) {
if(!sieve[i]) {
++primes;
for (int temp = 2*i; temp<number; temp += i)
sieve[temp] = true;
}
}
std::cout << "found: " << primes << " Primes\n";
return 0;
}
If n is big enough to cause memory allocation error program will crash due to incorrect memory allocation error handling here
A = new bool[n];
if(A == 0)
{
cout << "Memory cannot be allocated";
return 0;
}
new doesn't return 0 on error, but throws std::bad_alloc that doesn't get catched, which in turn will lead to unexpected() then terminate() and finally abort() to be called.
Correct version would be:
try
{
A = new bool[n];
}
catch (std::bad_alloc& ba)
{
std::cerr << "Memory cannot be allocated: " << ba.what() << '\n';
}
Run this in a debugger to determine where the crash is and debug from there. It will most likely be apparent at that point.
You can do this either from an IDE or from command line. In the latter case compile with -g and run in a program such as gdb. Google something like "gdb cheatsheet" to get started.