Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 3 years ago.
Improve this question
I tried sorting this array in ascending order and I got reply saying RUNTIME error(SIGSEGV). Can Anybody explain ?
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, arr[1000];
cin >> n;
for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);
sort(arr, arr + n);
for (int i = 0; i < n; i++)
cout << arr[i] << endl;
return 0;
}
When you get input from a user that is used to populate an array, you should always validate the input before using it. If the user wants to enter 1001 numbers or more, or even a negative amount, you will access the array out of bounds and your program has undefined behaviour.
A better alternative is to use a std::vector to allocate just as much space as you need. One possible solution:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
size_t n;
if(std::cin >> n) { // check that the user actually entered a number
std::vector<int> arr(n); // create a vector with n elements
for(size_t i=0; i<n; ++i)
std::cin >> arr[i];
std::sort(std::begin(arr), std::end(arr));
for(size_t i=0; i<n; ++i)
std::cout << arr[i] << '\n';
}
}
You're allocating space for only 1000 elements, thereby causing segmentation fault if n is more than that, because scanf will try to put 1001-th element in memory location un-allocated to arr. Since you're using C++, Please use std:vector to avoid such pitfalls.
Related
This question already has answers here:
Uninitialized variable behaviour in C++
(4 answers)
Closed 1 year ago.
Please help me with this strange problem where the input value is given as 4 (i.e. n = 4) and after a for loop the same value is getting displayed as 2, but why? It was not used anywhere (AFAIK) and it shouldn't get changed (I have no clue about it).
The original problem on HackerRank.
MY CODE >>
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n;
int arr[n];
cin >> n; // input given from stdin is 4
cout << n << "\n"; // outputs 4
for(int i=0; i<n; i++){
scanf("%d",&arr[i]);
}
cout << n << "\n"; // outputs 2 (but why?)
for(int i=n-1; i>=0; i--){
printf("%d ",arr[i]); // if it were n = 4, then i will go from 3 to 0, but it goes from 1 to 0 (as n=2, but again, why?)
}
return 0;
}
Thank you for any help!
int n;
int arr[n]; // <<<<<< I magically know what n will be after the user types it!
cin >> n; // input given from stdin is 4
First of all, that's not even legal in C++. As a gcc extension to support C style VLA's, what is the value of n when the array declaration is seen? You have not read it yet!!
Instead, use:
int n;
cin >> n;
std::vector arr(n);
Although this still is not the "C++ way" as you are pre-defining the entire collection and then assigning to each element in turn; as opposed to adding each element to the collection. This is not a big deal with an int but more generally you don't want dead unused items in a collection; rather they simply don't exist at all.
std::vector arr; // don't pre-allocate any size
for(int i=0; i<n; i++){
int val;
scanf("%d",&val); //<<< uhhhhhh. you know about `cin` why this?
arr.push_back(val);
}
Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 2 years ago.
Improve this question
Here is all of my code:
#include <fstream>
#include <vector>
#include <algorithm>
#include <set>
#include <iostream>
using namespace std;
int main(){
ifstream fin("cereal.in");
ofstream fout("cereal.out");
int n, m, f, s;
cin >> n >> m;
int c1[n];
int c2[n];
for(int i = 0; i < n; i++){
cin >> c1[i] >> c2[i];
c1[i]--;
c2[i]--;
}
vector<int> fm(m, -1);
set<int> fs;
vector<int> ans;
for(int i = n-1; i >= 0; i++){
if(fs.find(c1[i]) == fs.end()){
fs.insert(c1[i]);
}else{
if(fs.find(fm[c1[i]]) == fs.end()){
fs.insert(fm[c1[i]]);
}
}
fm[c1[i]] = c2[i];
ans.push_back(fs.size());
}
for(int i = 0; i < n; i++){
cout << ans[i] << endl;
}
}
In the first for loop when i = n-1, I'm getting a Segmentation fault: 11. I used a cout call after the cin in that for loop to find this information.
What is the reason for this? It was working fine a couple of minutes ago and I didn't even touch this part of the code and it stopped working. I'm using VS Code, but even when I use an online compiler it doesn't work. Here is the input I am giving:
4 2
1 2
1 2
1 2
1 2
Please help me. This isn't the first time I'm having a problem like this.
for(int i = n-1; i >= 0; i++){ // <------
if(fs.find(c1[i]) == fs.end()){
fs.insert(c1[i]);
}else{
if(fs.find(fm[c1[i]]) == fs.end()){
fs.insert(fm[c1[i]]);
}
}
fm[c1[i]] = c2[i];
ans.push_back(fs.size());
}
Change to i--. You're accessing c1[i] with out of bound index.
You have an array index out-of-bounds bug, causing the program to access data where it shouldn't.
for(int i = n-1; i >= 0; i++){
In the above statement the integer i wraps around until it overflows, thus indexing c1 into forbidden regions of memory.
The OS is alerted of the memory violation and killed the misbehaving program. When this happens the program is said to encounter a segmentation fault.
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 2 years ago.
Improve this question
I am getting an error when i run this code. The error code is 0xC00000FD and I can't seem to find a fix for what i need. Can someone please help me? Here's the code:
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int n;
int arr[n];
int i;
int sum=0, avg=0;
cout<<"array lengh: ";
cin>>n;
cout<<"Enter "<<n<<" array elements: ";
for(i=0; i<n; i++)
{
cin>>arr[i];
sum = sum + arr[i];
}
cout<<"\nThe array elements are: \n";
for(i=0; i<n; i++)
{
cout<<arr[i]<<" ";
}
cout<<"\n\nSum of all elements is: "<<sum;
avg = sum/10;
cout<<"\nAnd average is: "<<avg;
getch();
return 0;
}
There are two major problems in your code. First, C++ does not have "variable length arrays" (VLAs), although some compilers support them as an extension.
More importantly, even if your compiler does support them, you are attempting to define the size of your arr before you have read the value of n.
To fix these issue you should: (a) use the std::vector container, rather than a plain array; and (b) only declare that after you have read in the value of n.
Here's a 'quick fix':
#include <iostream>
#include <conio.h>
#include <vector> // For the "std::vector" definition
using namespace std;
int main()
{
int n;
// int arr[n]; // Here, the value of "n" is undefined!
int i;
int sum=0, avg=0;
cout<<"array lengh: ";
cin>>n;
std::vector<int> arr(n); // This can now be used 'almost' like a plain array
cout<<"Enter "<<n<<" array elements: ";
for(i=0; i<n; i++)
{
cin>>arr[i];
sum = sum + arr[i];
}
cout<<"\nThe array elements are: \n";
for(i=0; i<n; i++)
{
cout<<arr[i]<<" ";
}
cout<<"\n\nSum of all elements is: "<<sum;
avg = sum/10;
cout<<"\nAnd average is: "<<avg;
getch();
return 0;
}
Standard C++ does not support variable length arrays. std::vector can accomplish what you want. It is also possible to allocate memory of the desired size with new int[size] and use a pointer to reference the data rather than an array. However, this doesn't have any bounds checking, so there is the possibility of memory corruption. And the allocated memory must be explicitly freed with delete[]. So std::vector is my preferred solution.
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
so I have this code that with a function is supposed to take all the numbers in a 2D array and print them to the second power but my code keeps throwing segmentation fault and i don't know why
#include <bits/stdc++.h>
using namespace std;
void er(int arr[][100000000], int, int);
int main()
{
int n, m;
cin >> n >> m;
int arr[n][100000000];
er(arr, n, m);
return 0;
}
void er(int arr[][100000000], int n, int m)
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> arr[i][j];
arr[i][j] *= arr[i][j];
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cout << arr[i][j];
}
}
}
Using
int arr[n][100000000];
is problematic on two accounts.
VLAs are not standard C++. It is supported by some compilers as an extension.
The size 100000000 is too large for a variable on the stack. Changing that to 100 and making sure that m is less than or equal to 100 will most likely work as long as your compiler supports VLAs.
A better alternative would be to use std::vector.
int n, m;
cin >> n >> m;
std::vector<std::vector<int>> arr(n, std::vector<int>(m));
Of course, that will require you to change the function er accordingly.
In addition, please don't use
#include <bits/stdc++.h>
See Why should I not #include <bits/stdc++.h>? for further details.
Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 4 years ago.
Improve this question
I wrote a code,it will find the max one and min one in an arr by vector
but I simply don't know what I've made an error.
Every time I try it return zero for me.lol
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
int a[999];
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
vector<int> arr(a[1], a[n]);
int max = *max_element(arr.begin(), arr.end());
int min = *min_element(arr.begin(), arr.end());
int dis = max - min; cout << dis << endl;
return 0;
}
What's wrong with my code [?]
Honestly, almost everything.
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
using namespace std; can cause harm, not in small examples like this, but better don't get used to bad habits.
int main()
{
int a[999];
You allocate space for 999 elements. What if the user enters 1000 for n ?
int n;
cin >> n;
Array indices start at 0 not at 1. Lets say the user enters 999 then you are still going out of bounds invoking undefined behaviour because a[999] is not an element of the array.
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
You are calling the std::vector constructor that sizes the vector to hold a[1] elements with value a[n]. This is not copying the elements from the array to the vector! All elements will have the same value, hence you always get 0 as the result.
vector<int> arr(a[1], a[n]);
int max = *max_element(arr.begin(), arr.end());
int min = *min_element(arr.begin(), arr.end());
This is not really wrong, but written unnecessarily complicated. max_element returns an iterator and you can use eg. std::distance to get the distance between two iterators.
int dis = max - min; cout << dis << endl;
return 0;
}
You could write it like this
#include<iostream>
#include<algorithm>
#include<vector>
int main()
{
std::vector<int> x;
int n;
std::cin >> n;
x.resize(n);
for (auto& e : x) std::cin >> e;
auto max = std::max_element(x.begin(), x.end());
auto min = std::min_element(x.begin(), x.end());
std::cout << std::distance(max,min) << "\n";
return 0;
}
Live Demo
PS: Be careful with std::distance. Prior to C++11 it was undefined behaviour to call it with a second argument that cannot be reached from the first iterator passed by going forward. Also note that there is std::minmax_element that will give you both iterators from only traversing the vector once.