Segmentation Fault whenever using vector<> - c++

int main()
{
int n;
cin >> n;
char* temp_char;
vector<string> arr;
for (int i = 0; i < n; i++)
{
cin >> temp_char;
}
return 0;
}
Hi, whenever I have vector<string> arr; in this program, no matter I actually use this variable arr or not, after the first cin in the first forloop, I receive segmentation fault, don't know why is this happening? I do need to use vector<string> in the later programming.
I'm compiling with g++ under Ubuntu, any help would be much appreciated!

char* temp_char;
vector<string> arr;
for (int i = 0; i < n; i++)
{
cin >> temp_char;
}
Why the pointer?
What happens here is that you create a char* which points to an undefined location. std::istream (of which std::cin is an object) provides a special way to read input into a char*, which however works only when the target char* points to valid memory.
Otherwise, the behaviour is undefined, which means anything can happen, including crashes.
The solution is not use pointers but std::getline:
#include <iostream>
#include <string>
#include <vector>
int main()
{
int n;
std::cin >> n;
std::cin.ignore();
std::vector<std::string> arr;
for (int i = 0; i < n; ++i)
{
std::string line;
std::getline(std::cin, line);
arr.push_back(line);
}
}

I'm not sure in your code, but I think you have to use
char temp_char
insted of
char* temp_char
or at least allocate some memory to temp_char:
#include <iostream>
#include <vector>
int main()
{
int n;
std::cin >> n;
char* temp_char = new char[100];
std::vector<std::string> arr;
for (int i = 0; i < n; i++)
{
std::cin >> temp_char;
arr.push_back(temp_char);
}
for (auto s : arr)
std::cout << s << std::endl;
return 0;
}

Related

How to cin to a back_inserter or any inserter in c++?

So I was thinking of simplifying this snippet
#include <bits/stdc++.h>
using namespace std;
int n;
vector<int> A;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n;
for (int i = 0; i < n; i++) {
int tmp;
cin >> tmp;
A.push_back(tmp);
}
}
And because I have read about inserters and back_inserters recently I thought of using them right away and this is what I came up with
#include <bits/stdc++.h>
using namespace std;
int n;
vector<int> A;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n;
for (int i = 0; i < n; i++) cin >> *back_inserter(A);
}
But for some reason the compiler spits a gigantic error message which I can't fit here so here is the first sentence only as I think it is the most relevant.
error: no match for 'operator>>' (operand types are 'std::istream' {aka 'std::basic_istream<char>'} and 'std::back_insert_iterator<std::vector<int> >')
Thanks for your help!
NOTE: before anybody comments on the use of global variables and the using namespace line, this code was
intended for use only in competitive programming.
In this case where you are just reading space separated values from the input stream until it ends, you can use std::copy to get the values from the stream. That would look like
std::copy(std::istream_iterator<int>(cin),
std::istream_iterator<int>(),
std::back_inserter(vector_name));
You could read into a temporary variable.
for (int k, i = 0; i < n; i++) cin >> k, back_inserter(A) = k;
# or nicer:
for (int i = 0; i < n; i++) {
int k;
cin >> k;
back_inserter(A) = k;
}
You could provide the missing overload and read into temporary variable in it:
template<typename T>
std::istream& operator>>(std::istream& is, std::back_insert_iterator<std::vector<T>> obj) {
T tmp;
is >> tmp;
obj = tmp;
return is;
}
int main() {
for (int i = 0; i < n; i++) cin >> back_inserter(A);
}

Segmentation fault caused by simple c++ code

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;
}

Segmentation fault in a program that reverses a dynamically allocated array

I was doing a test and the online test engine showing segmentation error, which is confusing because with no further details, and I checked the pointer no NULL and they work pretty fine, but don't how array here works. Because when debugging, everything is fine, until I try to cout/print out the array. it's reporting a is crushed here and break. I can do nothing here if it break, and I hit break or continue. if I continue, it runs just fine. so I was really confused.
My computer is windows 7, I run code in visual studio 2010 c++.
Debugging is not that clear to solve the problem, and I am learning c++ not very efficient.
Solve with Array need dynamic allocation.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
void reverseArray(int size, int num[]) {
if(size>1) {
int *p = &num[size-1];
int *f = num;
for(int i = 0;i < size/2; i++){
swap(*p, *f);
p--;
f++;
}
}
}
int main() {
int len;
int a[len];/This is the bug, can't use uninitialized var assign array/
cin >> len;
for(int i = 0; i < len; i++){
cin >> a[i];
}
reverseArray(len, a);
for(int i = 0; i < len; i++){
cout << a[i] << " ";
}
return 0;
}
This has something to with dynamic allocation, when I work in java, I create a new array.
I have to
int[] newArray = {2,4,1,2,3};
or
int[] newArray = new int[] {2,4,1,2,3};
Finally, this problem is solved, which makes me very happy.
Reading and learning is very important, coding is also important.
Thanks all,
And using vector instead of using array.
It would be easier.
#include <cstdio>
#include <vector>
#include <iostream>
using namespace std;
int main() {
int a;
int len;
vector<int> myvector;
cin >> len;
for(int i = 0; i < len; i++){
cin >> a;
myvector.push_back(a);
}
reverse(myvector.begin(), myvector.end());
for(int i = 0; i < len; i++){
cout << myvector[i] << " ";
}
return 0;
}
Using Array again(I doubt the following code):
#include<iostream>
//#include<cstdlib>
using namespace std;
void reverseArray(int size, int nums[]){
if(size > 1){
int *p = &nums[size-1];
int *q = nums;
for(int i = 0; i< size/2; i++){
swap(*p, *q);
p--;
q++;
}
}
}
int main(){
int len;
cin >> len;
int *a = new int[len];//a point to the first ele.
for(int i = 0; i< len; i++){
cin >> a[i];
}
reverseArray(len, a);
for(int i = 0; i < len; i++){
cout << a[i] << " ";
}
delete [] a;
return 0;
}
It worked perfect on my laptop, which is confusing because a is pointer, but I use it like an array. It shouldn't be working......
Final Array version:
http://ideone.com/ZMsD35
Done perfectly.
#include<iostream>
using namespace std;
int main(){
int len;
cin >> len;
int *a = new int[len];
for(int i = 0; i< len; i++){
cin >> a[i];
}
reverse(a, a+len);
for(int i = 0; i< len; i++){
cout << a[i];
}
delete [] a;
system("pause");
return 0;
}
The most likely reason for a segfault is the input. When the testing software passes len of size sufficient to overflow the automatic storage area, your program crashes on this line:
int a[len];
The exact value of len is system-dependent, but an input of 1,000,000 should do it on most common systems.
The fix is really straightforward - replace the declaration with
int a* = new int[len];
This will place the data in dynamic memory, rather than the automatic memory. It will also make your program standard-compliant, because variable-length arrays in C++ are an extension to standards.
Don't forget to delete a once you are done to avoid memory leak:
delete[] a;

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);

Dynamic array from an input file

I'm a beginner, so I'm sorry if this is really dumb question/problem.
The assignment that I have is printing out a dynamic array from an input file. I tried googling it and I found some similar problems... but the answers were all like "use vectors" etc but we haven't learned those yet. It's also said that a function must be used. This is what I came up with:
#include <iostream>
#include <fstream> //file input
using namespace std;
int *out(int *arr, int siz){
arr = new int[siz];
for (int i = 0; i < siz; i++) {
cout << arr [i] << " ";
}
return arr; //this should print out the array later???
}
int main(){
int siz;
int *arr;
ifstream inf ("input.txt");
inf >> siz; //
for (int i = 0; i < siz; i++) {
inf >> arr[i];
}
inf.close();
cout << "This array contains following elements: ";
*arr = *out(arr, siz) ;
delete[] arr;
return 0;}
So, it doesn't give any errors with Dev-C++ but when I try to run it, it crashes. I tried debugging it and then it gave me "segmentation error" or something like that. Then of course, I googled it and there must be something wrong with the pointers, right? Could you help me out? Thanks.
You are trying to access arr, when arr has not been allocated or initialized to a valid array. Your main needs to allocate arr before using arr to populate elements:
So, here's the changed version:
#include <iostream>
#include <fstream> //file input
using namespace std;
void out(int *arr, int siz){
for (int i = 0; i < siz; i++) {
cout << arr [i] << " ";
}
}
int main(){
int siz;
int *arr;
ifstream inf ("input.txt");
inf >> siz;
arr = new int[siz]; // added
for (int i = 0; i < siz; i++) {
inf >> arr[i];
}
inf.close();
cout << "This array contains following elements: ";
out(arr, siz);
delete[] arr;
return 0;
}
arr is an uninitialized pointer.
Do arr = new int[size]; before you read data into arr.
You haven't allocated memory to the array, which you'd likely need to do with malloc. Once you've read in the size of the array, allocate the memory.
inf >> siz;
arr = malloc(siz * sizeof(*int));
//Rest of program
//delete[] arr; <- you use this with the new keyword
free(arr); //Use 'free' with malloc
return 0;
I think what you want might be sth like this
#include <iostream>
#include <fstream>
int main(){
int siz(0);
std::ifstream inf ("input.txt");//Assume that the input file and this file are in the same folder
inf >> siz; //Assume that the first number in input file is the size of array
int *arr=new int[siz];
for (int i = 0; (siz-i)&&inf ; ++i) {
inf >> arr[i];
}
inf.close();
std::cout << "This array contains following elements: ";
for (int i = 0; siz -i ; ++i ) {
std::cout << arr [i] << " ";
}
delete[] arr;
return 0;
}