Segmentation fault core dumped vector pointer [closed] - c++

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
void printTop5()
{
int counter = 1;
int x, y;
float civ;
cout << "Total no. of records available = " << pointVector.size();
cout << "Printing top 5 exploration destinations....";
sort(pointVector.begin(), pointVector.end(), ascendingCiv);
for (int i = 0; i < 5; i++)
{
PointTwoD p1 = pointVector[i];
x = p1.getX();
y = p1.getY();
civ = p1.getCivIndex();
cout << counter << ")\t";
if (civ > 0)
{
cout << "Civ idx: " << civ << " ; at sector(" << x << "," << y < ")\n";
}
else
cout << "<No records available>";
}
}
bool ascendingCiv(const PointTwoD &d1, const PointTwoD &d2)
{
return d1.getCivIndex() > d2.getCivIndex();
}
When I run this function I get this fault whereby it says segmentation fault core dumped. Any idea? Heard its about some memory problem.

One issue is that you are not checking whether you actually have at least 5 elements in your vector:
for (int i = 0; i < 5; i++)
{
PointTwoD p1 = pointVector[i];
If i is out-of-bounds of the vector, accessing pointVector[i] would invoke undefined behavior.
The loop condition can be changed to the following:
#include <algorithm>
//...
size_t loopEnd = std::min(pointVector.size(), 5);
for (size_t i = 0; i < loopEnd; i++)
{
PointTwoD p1 = pointVector[i];
The loop will either go up to the size of the vector or 5 elements, whichever is smaller.

Related

Index of vector of strings in c++ [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have a vector of string including :- chemistry physics maths.
I want to access first character of each word ie c of chemistry p of physics and m of maths. How to do that?
You can output the first index element through this process.
I have made a 2D vector and applied a for loop so each row of the vector's first element is printed.
#include <iostream>
#include <vector>
int main()
{
std::vector<std::string> vec = {"chemistry", "maths", "physics"};
for(int i=0;i<vec.size();i++)
{
std::cout << vec[i][0];
}
return EXIT_SUCCESS;
}
You can also use a range based for loop
for (auto &i : vec)
std::cout << i[0] << " ";
The output will be
c m p
You can treat it like a 2D matrix of characters.
Given the vector of strings:
std::vector<std::string> vec = {"chemestry", "physics", "math"};
You can use a normal loop to access all first characters:
for (int i = 0; i < vec.size(); i++)
std::cout << vec[i][0] << " ";
Or a range based loop:
for (auto &str : vec)
std::cout << str[0] << " ";
Output:
c p m
I think this code should do the trick. If not then the Compiler is being a racist and doesn't like you that much. In that case you can just go-to your old buddy cpp.sh :D
String is a char Array and you can access it's contents from indexes like so
std::string str = "Hello";
std::cout << "First Index: " << str[0];
Output:-
H
Same goes for the vector as well
std::vector <char> str = "World!";
std::cout << "First Index: " << str[0];
Output:-
W
Now if you combine those two, it makes it a 2D Array so you have to access it like you access data from a 2D Array/Matrix.
std::vector <std::string> str = {"Hello", "World", "!"};
std::cout << "First Index Of Element 1: " << str[0][0] << std::endl
<< "First Index Of Element 2: " << str[1][0] << std::endl
<< "First Index Of Element 3: " << str[2][0] << std::endl;
Output:-
H
W
!
Program:-
#include <iostream>
#include <vector>
int main() {
std::vector <std::string> vec = {"chemistry", "physics", "math"};
for (int i=0; i < vec.size(); i++) { //-- size(); Function gives the size of a vector
std::cout << vec[i][0] << std::endl;
}
return 0;
}
Output:-
c
p
m
Press any key to continue...

What exactly does this compiler error want me to perform? [closed]

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
Thank you in advance for reading ! So this is the code :
#include<iostream>
#include<vector>
std::vector<int> MonkeyCount(int n);
int main() {
MonkeyCount(4);
return 0;
}
std::vector<int> MonkeyCount(int n) {
std::vector<int> MonkeyCountV;
for (unsigned int i = 1; i <= n; i++) {
MonkeyCountV.push_back(i);
}
for (unsigned int i = 0; i <= MonkeyCountV.size(); i++) {
std::cout << MonkeyCount.at(i) << " ";
}
return MonkeyCountV;
}
and the error is on line 23 : error C2227: left of '->at' must point to class/struct/union/generic type
Now i red something about this, but i use this from an example i found on the internet on how to print a vector, and in that exaple, in works. The exaple is this :
#include <iostream>
#include <vector>
void print(std::vector<int> const& input);
int main()
{
std::vector<int> input = { 1, 2, 3, 4, 5 };
print(input);
return 0;
}
void print(std::vector<int> const& input)
{
for (unsigned int i = 0; i < input.size(); i++) {
std::cout << input.at(i) << ' ';
}
}
std::cout << MonkeyCount.at(i) << " ";
Should be:
std::cout << MonkeyCountV.at(i) << " ";
The way you have it is trying to do ".at(i)" on the function itself.
The name of your vector is MonkeyCountV but in the cout statement you are using MonkeyCount which is actually the name of your function. Make sure you have your variables name typed correctly.

C++ "Program.exe has stopped working" [closed]

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
In no way I can solve why I'm getting the error in the screenshot when entering the first value and trying to proceed.
The error happens only with code below.
Any help would be appreciated!
Error screenshot
//Darbas40
#include <io.h>
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
int n,
u,
m,
ms,
v,
vs,
i;
double vidvaikinu,
vidmerginu;
n = 7; m = 0; v = 0; ms = 0; vs = 0;
for (i = 1; i <= n; i++)
{
wcout << "Iveskite mokiniu ugius: "; cin >> u;
if (u > 0)
{
m++;
ms = ms + u;
}
else if (u < 0)
{
v++;
vs = vs + u;
}
vidmerginu = ms / m;
vidvaikinu = fabs(vs / v);
}
wcout << " " << endl;
wcout << "vidvaikinu = " << vidvaikinu << ", vidmerginu = " << vidmerginu << "." << endl;
return 0;
}
You'll get a divide by zero error if u <= 0 in:
vidmerginu = ms / m;
because m is set to 0 and not incremented.
And a divide by zero error if u >= 0 in:
vidvaikinu = fabs(vs / v);
because v is set to 0 and not incremented.

trying to solve project euler number 14 [closed]

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 7 years ago.
Improve this question
I´m trying to solve project euler problem number 14 and i have the code almost ready, but it keeps me giving the wrong answer.. Why it doesn't count more steps?? Thanks, sorry for the lack of commentary..
#include <iostream>
int collatz_length(int number);
int main() {
using namespace std;
int size_sequence, max_sequence = 0, number_ = 1000000, num;
while (number_>1) {
size_sequence = collatz_length(number_);
if (size_sequence > max_sequence) {
max_sequence = size_sequence;
num = number_;
cout << "size " << size_sequence
<< " starting number " << num << endl;
}
number_--;
}
cout << "The longest sequence has "
<< max_sequence << " steps, starting from the number: " << num << endl;
cin.get();
return 0;
}
int collatz_length(int number) {
using namespace std;
int size_sequence = 0;
while (number > 1) {
if ((number % 2) == 0){
number /= 2;
}
else {
number = (3 * number + 1);
}
size_sequence++;
}
return size_sequence;
}
It is possible that 3*n+1 will overflow an int. Perhaps you should use a uint64_t?

handling arrays in class declaration [closed]

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 7 years ago.
Improve this question
I just wrote a simplified implementation of the stack data structure in a class, but the handling of an integer array is behaving in a way that I can't seem to understand.
The same snippet of code as in push() will give the behavior I expect, but in this program assigning a value at a certain array position will assign the value to the index variable>
#include <iostream>
using namespace std;
class stack
{
public:
stack(int size)
{
ar_size = size - 1;
array[ar_size];
index = 0;
}
void push(int value)
{
cout << "index; " << index << endl; //will output 0
cout << "value: " << value << endl; //will output 8
array[index++] = value;
cout << "index; " << index << endl; //will output 8
cout << "value: " << value << endl; //will output 8
cout << "array: " << array[index] << endl; //will output what seems to be a memory address
}
int pop()
{
cout << "index; " << index << endl; //will output 8
return array[index--];
}
private:
int ar_size;
int array[];
int index;
};
int main()
{
stack tower(64);
tower.push(8);
int r = tower.pop();
cout << "pop: " << r << endl; //will output what seemed to be a memory address
return 0;
}
Here is the corrected code of your example:
#include <iostream>
class stack
{
public:
stack(int size)
{
ar_size = size - 1;
array = new int[size];
index = 0;
}
void push(int value)
{
array[index++] = value;
}
int pop()
{
return array[--index];
}
~stack()
{
delete array;
}
private:
int ar_size;
int *array;
int index;
};
int main()
{
stack tower(64);
tower.push(8);
int r = tower.pop();
std::cout << "pop: " << r << std::endl; //Will output 8 :)
return 0;
}
There were several issues with it.
As pointed out in the comments array[ar_size]; in your constructor did not do what you wanted it to. array[ar_size]; accesses the array at the given index, it does not allocate the array for you. I've fixed the problem so that the array is now allocated via new and deleted when the stack is destroyed.
return array[index--]; was not right as well. You need to lower the index before accessing the element. return array[--index]; is now right.
You're missing a BUNCH of checks so that your stack does not cause a segfault or any other undefined behaviour. You need to check if you can still push values or if you can pop values and so on.
I hope it clears things up a bit.
You could use dynamic memory allocation.Something like this
private:
int ar_size;
int *array;//pointer to array
int index;
and then in the constructor
stack(int size)
{
ar_size = size - 1;
array=new int[ar_size];
index = 0;
}
Since this is dynamic memory allocation make sure to free the allocated memory.You can have a destructor
~stack()
{
delete[] array;
}
Another point is after you push an element,you increase the index by 1.So now index does point to the next insertion point in the stack.So if you do a pop operation it will remove an element from index location but there is no element there yet.So you can change your pop function to
int pop()
{
cout << "index; " << index << endl; //will output 8
return array[--index];//now index will point to the top element
}
I think you want array = new int[ar_size]; instead of array[ar_size];. You'll need to make a destructor that does delete [] array; as well then.