Segmentation fault caused by simple c++ code - c++

Absolute beginner here. I'm trying to solve this but get a segmentation fault. I tried searching for a solution but couldn't find the reason why this doesn't work.
To reproduce the error simply copy the code below and paste it into the editor under the link above.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
//using namespace std;
int main() {
int n, q;
std::cin >> n >> q;
std::vector<std::vector<int>> arr;
// handle n lines representing the arrays
for (int i = 0; i < n; i++) {
std::vector<int> numbers;
std::string line;
getline(std::cin, line);
std::istringstream iss(line);
int enterNumber;
while (iss >> enterNumber)
{
numbers.push_back(enterNumber);
}
arr.push_back(numbers);
}
// handle q lines representing i, j
int x, y;
for (int i = 0; i < q; i++) {
std::cin >> x >> y;
std::cout << arr[x][y];
}
return 0;
}
What am I missing? Why doesn't it work?
Input that causes the segmentation fault:
2 2
3 1 5 4
5 1 2 8 9 3
0 1
1 3
Expected output:
5
9

1) getline(std::cin, line); . Line contains space and numbers.
2) Handle spaces in lines
3) Handle first int in line for array length. (You tried to add array length in array itself)
Here is working code for reference. (Passed all test cases)
#include <vector>
#include <iostream>
using namespace std;
int main() {
int n, q;
cin >> n >> q;
vector< vector<int> > arr;
int temp, array_count;
for(int i = 0; i < n; i++) {
vector<int> numbers;
cin>>array_count;
for(int j = 0; j < array_count; j++) {
cin>>temp;
numbers.push_back(temp);
}
arr.push_back(numbers);
numbers.clear();
}
// handle q lines representing i, j
int x, y;
for (int i = 0; i < q; i++) {
cin >> x >> y;
cout << arr[x][y]<<"\n";
}
return 0;
}

To fix the segmentation fault simply add std::cin.get(); after the first std::cin(third line in your main function).
The segmentation fault happened because getline(std::cin, line);returned an empty string during the first iteration of the for loop. See this.
Note that even after fixing the segmentation fault issue your code is still wrong (doesn't solve the challenge) :p
Try this:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
//using namespace std;
int main() {
int n, q;
std::cin >> n >> q;
std::cin.get();
std::vector<std::vector<int>> arr;
// handle n lines representing the arrays
for (int i = 0; i < n; i++) {
std::vector<int> numbers;
std::string line;
getline(std::cin, line);
std::istringstream iss(line);
int enterNumber;
while (iss >> enterNumber)
{
numbers.push_back(enterNumber);
}
numbers.erase(numbers.begin()); // because first value is k
arr.push_back(numbers);
}
// handle q lines representing i, j
int x, y;
for (int i = 0; i < q; i++) {
std::cin >> x >> y;
std::cout << arr[x][y] << std::endl;
}
return 0;
}

Related

Input file not being read from input.txt file

#include <bits/stdc++.h>
#include <iostream>
#include <fstream>
using namespace std;
typedef long long int ll;
int main()
{
istream in("input.txt", "r", stdin);
ofstream out("output.txt", "w", stdout);
int t;
in >> t;
while (t--)
{
ll n;
in >> n;
ll arr[n];
for (int i = 0; i < n; i++)
{
in >> arr[i];
}
sort(arr, arr + n);
double sum = 0;
for (int i = 0; i < n - 1; i++)
{
sum += arr[i];
}
double ans = (sum / (n - 1)) + arr[n - 1];
out << setprecision(9) << ans << endl;
}
return 0;
}
Note that I also changed my tasks.json file.
I changed my code according to what #john and #PepjinKramer said, but my inputs are not being read from the input.txt file and so nothing is shown in output.txt.
How do I solve this problem?
Some feedback to show how to reduce the "cargo cult" content of much C++ code out there :
// #include <bits/stdc++.h> <== NO not standard C++
#include <algorithm> // for sort
#include <iostream>
#include <fstream>
#include <vector> // for resizable arrays
#include <numeric> // for accumulate
#include <iomanip> // for setprecission
// using namespace std; <== NO will become a problem in big projects (nameclashes0
// typedef long long int ll; <== NO just use standard types in code e.g. std::size_t or std::int64_t
int main()
{
//istream in("input.txt", "r", stdin); // reading from file doesn't need anything from stdin
//ofstream out("output.txt", "w", stdout); // writing to a file doesn't need anything from stdout
// std::ifstream input{ "input.txt" };
// std::ofstream output{ "output.txt" };
// for testing manual input
auto& input = std::cin;
auto& output = std::cout;
std::size_t number_of_averages; // give variables more meaningful names then just 't'
std::cout << "input number of averages to calculate = ";
input >> number_of_averages;
for(std::size_t n = 0; n < number_of_averages; ++n )
{
//ll n; NO sizes of containters should be std::size_t not long long
//ll n;
//in >> n;
std::size_t number_of_values;
std::cout << "input number of values = ";
input >> number_of_values;
// ll arr[n]; // NO C++ doesn NOT have variable length arrays, use std::vector
std::vector<double> values(number_of_values);
// for (int i = 0; i < n; i++) // Do NOT use index based loops if you don't have to (out of bound bugs)
//{
// use range based for loops and learn about (const) references
for(auto& value : values)
{
std::cout << "input number : ";
input >> value;
}
// sort(arr, arr + n); // No use iteraters
std::sort(values.begin(), values.end());
// NO for summing collections use <algorithm> accumulate
/*
double sum = 0;
for (int i = 0; i < n - 1; i++)
{
sum += arr[i];
}
*/
auto sum = std::accumulate(values.begin(), values.end(), 0.0);
auto average = sum / static_cast<double>(values.size());
std::cout << "average = ";
output << std::setprecision(9) << average << std::endl;
}
return 0;
}

Why does this code output before even reading input?

My code below outputs 0, the value of max_explode, before even reading in my input. Why is this happening?
#include <iostream>
#include <vector>
#include <algorithm>
#define MAX 100
using namespace std;
int N,cnt=0;
vector<int> arr;
bool seen[MAX+1];
int main()
{
for (int i = 0; i < N; i++) seen[i]=false;
int max_explode=0;
for (int i = 0; i < N; i++)
{
int cow;
cin >> cow;
arr.push_back(cow);
}
sort(arr.begin(),arr.end());
cout << max_explode << "\n";
return 0;
}
You read input in a loop:
for (int i = 0; i < N; i++)
{
int cow;
cin >> cow;
arr.push_back(cow);
}
However, N is never explicitly initialized. Since it's a global variable, it's automatically initialized to 0, and your loop never runs.
There's a small issue in your 7th line to be specific. You have defined the variable N but haven't initialized a value to it.

[C++14]I'm using pair but no output

I was writing a code to sort and output the number by using "pair".
I tried some cases bat there was no output.
How should I rewrite the code?
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
int main()
{
int k, i, n;
cin >> n;
pair<int, int> a[n];
for (i = 0; i < n; i++) {
cin >> k;
a[i].first = -k;
a[i].second = i + 1;
}
sort(a, a + n);
for (i = 0; i++; i < n) {
cout << a[i].second;
}
}
for(i=0;i++;i<n){
You meant to write this as:
for(i=0;i<n;i++){

Convert char* to <string>

This is my first post, so please be understanding for me :)
I would like to use vector of strings to make sort data easy, but I need this string also to function fun1. So I would like to convert char* word to string str but i can't manage to do it. I was searching answer for my question but I didn't find.
Please help, here is code:
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <string.h>
using namespace std;
vector <string> tab;
vector <string> tab2;
int l['Z'+1];
void fun1(char *t)
{
for(int i = 0; t[i]; i++)
l[t[i]]++;
int j = 0;
for(int i = 'A'; i <= 'Z'; i++)
if(l[i])
{
t[j++] = i;
l[i--]--;
}
}
int main()
{
char * word;
string str;
ios_base::sync_with_stdio(0);
int z;
int n;
cin >> z;
while(z--)
{
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> word;
fun1(word);
str.assign(word, sizeof(word));
tab.push_back(str);
}
sort(tab.begin(), tab.end());
for(int i = 0; i < tab.size(); i++)
cout << tab[i] << endl;
}
}
Firstly, I have no idea, why you want to convert char* to string. In your solution firstly you have to allocate memory for chars
char *word = new char[HOW_MANY_CHARS]
But there is better solution. You can write:
cin >> str;
fun1(str);
tab.push_back(str);
And you have to change fun1 to:
void fun1(string &t);

Unexpected segmentation error

I wrote a really simple program, but it's crashing when I try to write the size of a queue (created with STL). I have no idea why, please help.
#include <queue>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n, i, x, cut = 0;
queue<int> que;
vector<int> vec;
cin >> n;
for (i = 1; i <= n; i++) {
cin >> x;
vec.push_back(x);
}
sort(vec.begin(), vec.end());
for (i = 0; i < n; i++)
que.push(vec[i]);
while (!que.empty()) {
cout << que.size() << '\n';
cut += que.front();
while (que.front() <= cut)
que.pop();
}
return 0;
}
You get an error because you call front while the queue is empty.
Just check if the queue is empty in your inner loop:
#include <queue>
#include <queue>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n, i, x, cut = 0;
queue<int> que;
vector<int> vec;
cin >> n;
for (i = 1; i <= n; i++) {
cin >> x;
vec.push_back(x);
}
sort(vec.begin(), vec.end());
for (i = 0; i < n; i++)
que.push(vec[i]);
while (!que.empty()) {
cout << que.size() << '\n';
cut += que.front();
while (!que.empty() && que.front() <= cut )
que.pop();
}
return 0;
}
Your code is actually crashing on the line:
while (que.front() <= cut)
Because you have a loop that may be true for the whole queue. The next line pops a value. At some point, your queue is empty and que.front() will crash.