Why does this code have a segmentation fault? - c++

I find that that while running this code it says:
Thread1:EXC_BAD_ACCESS(code=1,address=0x7fff3010efcc)
Code:
#include <iostream>
using namespace std;
int main()
{
int d[20],n,k,j,i,a[100000000],count=0;
//long long int i,a[100000000];
cin>>n>>k;
for(i=0;i<k;i++)
{
cin>>d[i];
}
for(i=0;i<n;i++)
{
a[i]=i;
}
for(i=0;i<n;i++)
{
for(j=0;j<k;j++)
{
if(a[i]%d[j]==0)
{
a[i]=0;
}
}
}
for(i=0;i<n;i++)
{
if(a[i]!=0)
{
count++;
}
}
cout<<count;
}

The stack has overflowed. There is no place for int a[100000000] as its size exceeds the default stack size (1MB on Windows)

If we don't know the values of n and k, we can't respond appropriately to your question.
By example, if you give the value 21 to k, you write (cin >> d[i]) d in position 20; this can cause the segmentation fault.
Suggestions:
1) run your program in a debugger
2) check the values for n and k
3) and use std::vector instead old C-style arrays and at() instead operator[] (by example: cin >> d.at(i), a.at(i) = i, etc. instead cin >> d[i], a[i] = i, etc.) because at() perform a bound checking.

Related

Partition of Array by Element given X

I Am Trying To Find Partition Of Array ,On Condition By Checking Variable x ,when less then x they will be on one side or else on another. but my code need some correction.
HERE am not able to find the error , i will be thankful to you if you help me.
Code is:-
#include<iostream>
using namespace std;
int partition(int arr[],int n,int x){
for(int i=0;i<n;){
if(arr[i]<x){
i++;
}
else if(arr[i]==x){
int temp=arr[i];
arr[i]=arr[n];
arr[n]=temp;
i--;
}
else if(arr[i]>x){
int temp=arr[i];
for(int j=i;j<n;j++){
arr[j]=arr[j+1];
}
arr[n]=temp;
i--;
}
}
return 0;
}
int main(){
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
int x;
cin>>x;
partition(arr,n,x);
for(int i=0;i<n;i++){
cout<<arr[i]<<"\t";
}
return 0;
}
Input >> array={2,10,15,1,3,15} ,x=10
Expected << {2,1,3,10,15,15}
Output I get << nothing .
The code isn't giving any output because, first, the "cin" and "cout" are in upper case which is syntactically incorrect, secondly, the variable j is in different case in loop statement and body inside the second else-if clause in the partition function, same goes for the "I" in the first for loop in the main() function. Sort this out and you should be good to go.
First in C++ the size of an array must be a compile-time constant. So for example, consider the following examples:
int n = 10;
int arr[n]; //INCORRECT
The correct way to write the above would be:
const int n = 10;
int arr[n]; //CORRECT
Similarly, in your code,
int n;
cin>>n;
int arr[n]; //INCORRECT because n is not a constant expression
Second, in your code, when you wrote:
arr[n] = temp; Undefined behavior
you're going out of bounds and so you have undefined behavior.
Solution
You can use std::stable_partition and std::vector to solve your problem as shown below:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
int n;
std::cout <<"Enter n:"<<std::endl;
std::cin >> n;
std::vector<int> arr(n); //create a vector of size n instead of an array
std::cout<<"Enter elements: "<<std::endl;
//iterate and take input from user
for(int &elem: arr){
std::cin >> elem ;
}
int x;
std::cout << "Enter x: "<<std::endl;
std::cin>>x;
//use std::partition
std::stable_partition(arr.begin(), arr.end(), [x](int i){return (i < x);});
std::cout<<"This is the partitioned vector: "<<std::endl;
for(int i=0;i<n;i++)
{
std::cout<<arr[i]<<"\t";
}
return 0;
}
Output
The output of the above program is as follows:
Enter n:
6
Enter elements:
2
10
15
1
3
15
Enter x:
10
This is the partitioned vector:
2 1 3 10 15 15
which can be seen here.

Why am I getting the wrong output for this C++ code? (one of the problem of hackerrank)

This is the program for printing out sum of array elements. It is showing run time error. The output is coming out to be 0 instead of printing out the sum of the elements.
#include<iostream.h>
using namespace std;
void simpleArraySum()
{
int ar[100],n,i,sum=0;
for(i=0;i<n;i++)
{
sum=sum + ar[i];
}
cout<<sum;
}
int main()
{
int ar[100],n;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>ar[i];
}
simpleArraySum();
return 0;
}
On this line in your main:
int ar[100], n;
You create an array of 100 elements. You later fill that array using cin
for(int i = 0 ; i < n ; i++)
{
cin >> ar[i];
}
Then you do nothing with that array. You are not calculating any sum. You let that array go, forgotten.
Then, you call a simpleArraySum function. That function is creating an entirely new, distinct array.
// v-----v------There
int ar[100],n,i,sum=0;
That array has no value assigned to it. In fact, reading from it is undefined behavior.
What you want is to receive that array in the arguments of your function:
void simpleArraySum(int* ar, int n) {
// ...
}
And call it like that in your main:
simpleArraySum(ar, 100);
You can avoid the issues of arrays and functions by not using them:
int main()
{
int quantity = 0;
std::cin >> quantity;
int sum = 0;
int value;
while (std::cin >> value)
{
sum += value;
}
std::cout << sum << "\n";
return EXIT_SUCCESS;
}
In simpleArraySum, the variable n is uninitialized. So this loop:
for(i=0;i<n;i++)
invokes undefined behavior when reading from n.
Also, you are summing a different array in the function, than the one you read in mian. It seems that you need to pass in the array from main to this function:
void simpleArraySum(int *ar, int n) {
and call it like this:
simpleArraySum(ar, n);
Finally, you don't even need a function for this, since there is an existing algorithm std::accumulate that you can use:
cout << std::accumulate(ar, ar + n, 0);
In the function, you're adding the elements of ar which is local to the function simpleArraySum() and is not of the array ar that is local to main().
So, pass the array and its length to the function and return its sum. Here is your corrected code:
#include<iostream>
using namespace std;
void simpleArraySum(int ar[], int n)
{
int i, sum = 0;
for(i=0;i<n;i++)
{
sum=sum + ar[i];
}
cout<<sum;
}
int main()
{
int ar[100],n;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>ar[i];
}
simpleArraySum(ar, n);
return 0;
}

Recursive function, which writes integer digits in an array(vector) in C++?

I have a C++ program, in which I have to create a recursive function that writes all the digits of a given positive integer in an array - in this case a vector.
However, when I compile the program and enter a number, it stops working. I want to ask why this happens?
#include <iostream>
#include <vector>
using namespace std;
vector <int> arr;
int temp;
int fill_Array(int num)
{
if(num>=1 && num<=9)
{
arr.push_back(num);
}
temp = fill_Array(num)%10;
arr.push_back(temp);
num/=10;
}
int main()
{
int n;
cin>>n;
fill_Array(n);
for(int i=0; i<arr.size(); i++)
{
cout<<arr[i]<<endl;
}
return 0;
}
In the given code, recursion function does not returning any value, so return type for that function have no use.
calling the function for recursion is in the wrong place. Correct code given below:
#include <iostream>
#include <vector>
using namespace std;
vector <int> arr;
int temp;
void fill_Array(int num)
{
if(num>=1 && num<=9)
{
arr.push_back(num);
}
else{
temp = num%10;
arr.push_back(temp);
fill_Array(num/=10);
}
}
int main()
{
int n;
cin>>n;
fill_Array(n);
for(int i=0; i<arr.size(); i++)
{
cout<<arr[i]<<endl;
}
return 0;
}
A couple of reasons I can see:
There is no conditional to stop the recusion so it will keep going until it runs out of stack or memory. I presume you want to stop when num is zero
fill_Array has no return value so will assign temp with some random value which will be pushed into the array
Also why use recursion for this when iterative would be easier and more obvious what it is doing

Why is IDEone showing runtime error even after getting the output?

What is wrong with my program ?
It works fine on my PC but in IDEone it gives the correct output but shows runtime error. Please help.
#include<bits/stdc++.h>
using namespace std;
struct student
{
int vote;
};
int main()
{
int t;
cin>>t;
while(t--)
{
int count=0;
int n;
cin>>n;
vector <int> a(n);
student s[n];
int k;
cin>>k;
for(int i=1;i<=n;i++)
{
s[i].vote=0;
}
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
int temp=0;
for(int i=1;i<=n;i++)
{
if(a[i] != i)
{
temp=a[i];
s[temp].vote++;
}
}
for(int i=1;i<=n;i++)
{
if(s[i].vote==k)
{
count++;
}
}
printf("%d\n",count);
}
return 0;
}
This is the error shown in IDEone :-
Error in `./prog': free(): invalid next size (fast): 0x085cca10
student s[n];
This declares an array called s. It contains n values. The values are s[0] through s[n-1] (you can count them all on your fingers, if you'd like, using a small number of n, such as 5).
for(int i=1;i<=n;i++)
{
s[i].vote=0;
}
This attempts to initialize values s[1] through s[n]. The only problem is that s[n] doesn't exist. The last value in the array is s[n-1]. This code will corrupt memory on the stack, resulting in undefined behavior.
The same bug also occurs with the a array.
The index values for both vector and array are zero based and goes up to n - 1. So
for(int i = 0; i != n; ++i)
would be better.
Now you write one element too far, which free finds out later when the data after the memory block is invalid.

Reversing an Array Results In SegFault

#include <iostream>
using namespace std;
/*
*
*/
int main() {
int k, in[k],reversea[k],i,m,n;
cin>>k;
for (i=0;i<k;i++){
cin>>in[i];
}
for (m=k-1;m>=0;m--){
for (n=0;n<k;n++){
in[m]=reversea[n];
}
}
for(i=0;i<k;i++){
cout<<reversea[i];
}
return 0;
}
I have no idea why it says segmentation fault even before i start debugging it. I compile another one on calculating the frequency of 1, 5, and 10 in an array of k numbers, and it says the same thing...
Here is the other one:
#include <iostream>
using namespace std;
int main() {
int k,i,m,n,count5,count1,count10;
int input[k];
cin>>k;
for (i=0;i<k;i++){
cin>>input[i];
}//input all the numbers
for(i=0;i<k;i++){
if (input[i]=1){
count1++;
}
if (input[i]=5){
count5++;
}
if (input[i]=10){
count10++;
}
}
cout<<count1<<"\n"<<count5<<"\n"<<count10<<"\n";
return 0;
}
Please help me. Thanks.
On this line
int k, in[k],reversea[k]
How are you supposed to initialize an array with k elements if k isn't initialized? The size of an array must be known at compile time not run time. If k isn't know until run time, use a std::vector
int k;
std::cin >> k;
std::vector<int> in(k);
std::vector<int> reversea(k);
Both your programs have two major faults.
You need to know the size of an array while creating it. In your code, k is still uninitialized and you are using this value as the size of your array. Instead, change it to
int k,i,m,n;
cin >> k;
int in[k];
int reversea[k];
While reversing the array, you should be filling reversea using values from in, and not the other way round. Also, you don't need 2 for loops, just use 1 for loop.
for (m=k-1; m>=0; m--){
reversea[m] = in[k-1-m];
}
In the second program, you again need to get the value of k before creating the array input[k].
You are testing for equality with a = instead of == . Change your code from
if (input[i]=1){
to
if (input[i] == 1) {