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 6 years ago.
Improve this question
I am trying to solve a CodeChef problem. Whenever I run it I get a segmentation fault. This is the link to the problem: Malvika is peculiar about color of balloons
Here is my code :
#include<iostream>
#include<cstring>
#include<algorithm>
int main(){
std::string balloonColors;
size_t numberOfAmber;
size_t numberOfBrass;
int t;
int results[t];
std::cin >> t;
for (int i = 0; i < t; i++){
int result = 0;
std::cin >> balloonColors;
numberOfAmber = std::count(balloonColors.begin(), balloonColors.end(), 'a');
numberOfBrass = std::count(balloonColors.begin(), balloonColors.end(), 'b');
if (numberOfAmber == 0 || numberOfBrass == 0){
result = 0;
}
if (numberOfAmber <= numberOfBrass){
result = (int)numberOfAmber;
}
else {
result = (int)numberOfBrass;
}
results[i] = result;
}
for (int x = 0; x < t; x++){
std::cout << results[x] << std::endl;
}
}
These lines is the problem:
int t;
int results[t];
You declare results using the uninitialized variable t. An uninitialized variable have an indeterminate value, and using it before initialization leads to undefined behavior.
You should use a std::vector here, and set its size once you get the actual size from the user:
int t;
std::vector<int> results;
std::cin >> t;
results.resize(t);
Arrays in C++ need to have a fixed size. You defined results with size t, which isn't fixed.
To use dynamic size, use a std::vector instead:
#include <vector>
...
int t;
std::cin >> t;
std::vector<int> results (t);
Related
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 1 year ago.
Improve this question
I'm making a simple number reverse program and I've tried many different ways to convert the string to an int but all I get is errors or "core dumped" while executing or compiling. I'm new to C++.
#include <bits/stdc++.h>
using namespace std;
void solve(){
string n, ans="";
cin >> n;
for(int i=0; i<n.length()+1;++i){
ans += n[n.length()-i];
}
int num = stoi(ans);
cout << ans << "\n";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >>t;
while(t--){
solve();
}
return 0;
}
Your for loop is accessing an out-of-bounds element of the n string on its first iteration: when i is zero, you are attempting to access the n.length() element of n but the last element is at position n.length() - 1. Remember that arrays, strings and other 'containers' in C++ start at element 0 and end at element n-1 – where n is the size (length) of the container.
You can fix this by starting your loop with i = 1 rather than with i = 0.
#include <iostream>
#include <string>
using std::string;
using std::cout, std::cin; // Pre C++17, you'll need 2 separate "using" statements.
void solve()
{
string n, ans = "";
cin >> n;
for (size_t i = 1; i <= n.length(); ++i) {
ans += n[n.length() - i];
}
int num = stoi(ans);
cout << num << "\n"; // I've changed to print "num" rather than "ans"
}
int main()
{
// For someone who is "new to C++," the following two lines are probably overkill...
// std::ios::sync_with_stdio(false);
// cin.tie(NULL);
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
Also please read Why should I not #include <bits/stdc++.h>? and Why is "using namespace std;" considered bad practice?
On the issue I've commented as "overkill," see: Significance of ios_base::sync_with_stdio(false); cin.tie(NULL); (especially the top/accepted answer).
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 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.
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.
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 6 years ago.
Improve this question
this program suppose to convert decimal to binary but somehow i screw it up
can some one point out the error for me?
thanks a lot
#include<conio.h>
#include<stdio.h>
int main(){
int a;
int b[20];
int q = 0;
printf("decimal : ");scanf("%d",&a);
while(a>0)) {
b[q]=a%2;
a=a/2;
q++;
}while(a>0);
printf("binary : ");
for (int i = q-1; i>=0;i--){
printf("%d",b[q]);
}
}
Corrected code is:
#include<conio.h>
#include<stdio.h>
int main(){
int a;
int b[20];
int q = 0;
printf("decimal : ");scanf("%d",&a);
while(a>0) {
b[q]=a%2;
a=a/2;
q++;
}
printf("binary : ");
for (int i = q-1; i>=0;i--){
printf("%d",b[i]);
}
}
You were printing b[q] instead of b[i]
There are some problems with your code:
you added an extra ")" of the first while;
the second 'while' is useless (the code is being repeated due to the first one)
you are not printing the elements you want (you should use var 'i'), what you are really printing is the value after the last 0/1 (because you are using 'q')
code should look like this:
#include <conio.h>
#include <stdio.h>
int main() {
int a;
int b[20];
int q = 0;
printf("decimal: ");
scanf("%d", &a);
while (a > 0) {
b[q] = a % 2;
a = a / 2;
q++;
}
printf("binary: ");
for (int i = q - 1; i >= 0; i--) {
printf("%d", b[i]);
}
}