C++ segmentation fault on programming exercise - c++

I am getting a segmentation fault error when trying to solve this programming marathon C++ exercise but I can't find the error anywhere:
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <vector>
#include <stdio.h>
#include <string.h>
using namespace std;
int main(void)
{
int m,n,i,di,x,y;
char* let;
cin >> n >> m;
x=0;
y=0;
for (i = 0; i < n; i++)
{
cin >> let >>di;
if ((strcmp(let,"S"))||(strcmp(let,"O"))){
di=(-di);
}
if ((strcmp(let,"N"))||(strcmp(let,"S")))
{
x=+di;
}
if ((strcmp(let,"L"))||(strcmp(let,"O")))
{
y=+di;
}
if ((y*y)+(x*x)>(m*m))
{
cout << "1";
return 0;
}
}
cout << "0";
return 0;
}

This code:
char* let;
cin >> let
stores user input to the memory pointed to by let.
This is misuse of an uninitialized pointer. cin trusts that you have pointed it to valid memory, but you haven't assigned anything to it. Where it points to is unknown.
The easiest solution would be to change let to a proper C++ std::string.

Related

free(): invalid pointer when using scanf

Hello guys so this is my code.
I could not use cin nor getline() so I had to use scanf.
It reads all the values in as expected but after entering the last value it says:
free(): invalid pointer ./comp: line 8: 877 Aborted (core dumped) ./$BIN
Anyways, here is the code.
Help would be appreciated.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
// n -> amount of lines of code.
// q -> amount of queries.
int n, q;
cin >> n >> q;
// Handle source code Input.
vector<string> v(n);
for (unsigned i = 0; i < n; ++i)
{
cout << "i: " << i << endl;
scanf("%s", &v[i]);
}
return 0;
}
scanf is designed to work with character buffers, not strings. You probably want to use std::string (it's more intuitive and manages memory for you), so scanf is a poor fit. There's a version of getline that works with string.
std::vector<std::string> v(n);
for (int i = 0; i < n; i++) {
cout << "i: " << i << endl;
std::getline(std::cin, v[i]);
}
The %s specifier of scanf() expects a pointer to a char[] array, not a std::string object. By reading directly into a std::string object, you are corrupting its internals.
So, you need to either:
read into a char[] first, then assign that to your std::string:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
// n -> amount of lines of code.
// q -> amount of queries.
int n, q;
cin >> n >> q;
// Handle source code Input.
vector<string> v(n);
char buf[256];
for (unsigned i = 0; i < n; ++i)
{
cout << "i: " << i << endl;
scanf("%255s", buf);
v[i] = buf;
/* or:
int len = scanf("%255s", buf);
v[i] = string(buf, len);
*/
}
return 0;
}
pre-allocate the std::string's internal character buffer, then read directly into it (note, this approach is only guaranteed to work in C++11 and later, but in practice will typically work in most implementations of std::string in earlier versions, too):
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
// n -> amount of lines of code.
// q -> amount of queries.
int n, q;
cin >> n >> q;
// Handle source code Input.
vector<string> v(n);
for (unsigned i = 0; i < n; ++i)
{
cout << "i: " << i << endl;
v[i].resize(256);
int len = scanf("%255s", &v[i][0]/* or: v[i].data() in C++17 and later */);
v[i].resize(len);
}
return 0;
}

I am trying to compile this code please review

using namespace std;
int main()
{
string dna1;
getline(cin, dna1);
string dna2;
getline(cin, dna2);
int hammingDistance=0;
for (int i=0; i < dna1.length(); ++i) {
if (dna1[i] !=dna2[i]) {
hammingDistance++;
}
}
cout <<"HammingDistance is: " << hammingDistance << '\n’;
}
So this is the code I have compiled but it seems to have some error this is from the website Rosalind to which I have added the link below:http://rosalind.info/problems/hamm/
As Michael Roy commented, you're missing the header files you need, iostream and string.
#include <iostream>
#include <string>
You need to format your code though. As it is, it's hard to read, in a regular production-size project, it would be impossible. I also don't recommend using the "using namespace std;" declaration. It's a bad beginner habit to get into.
Everyone has their own specific preferences, but this is roughly what your code should look like.
#include <iostream>
#include <string>
int main()
{
std::string dna1;
std::cin >> dna1;
//getline(cin, dna1);
std::string dna2;
std::cin >> dna2;
//getline(cin, dna2);
int hammingDistance = 0;
for (int i=0; i < dna1.length(); ++i) {
if (dna1[i] != dna2[i]) {
hammingDistance++;
}
}
std::cout <<"HammingDistance is: " << hammingDistance << '\n';
return 0;
}
I used the standard stream methods for input for consistency, but there's nothing technically wrong with other methods, as long as you don't use gets().

Reading arrays from file c++

I'm trying to make a program that so far only needs to read a file and saves its content in an array. the cout was a test to see if the words would be saved to the array but it didn't work. When executed all it does is print to screen empty spaces and finally the name of the file.
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <iostream>
#include <fstream>
#include <streambuf>
#include <ctime>
#include <time.h>
#define MAX 10000
void readFile(fstream& wordFile, string words[], int &wordarrayLength)
{
string word;
int i=0;
while(i < MAX)
{
getline(wordFile,word);
words[i] = word;
i++;
cout << words[i] << endl;
}
wordarrayLength = i;
wordFile.close();
}
int main()
{
string words[MAX];
int arraylength;
fstream file ("words.txt", ios::in);
readFile(file,words,arraylength);
}
I was missing the file the compiler was looking for. This code works fine.
Try something like this:
//since you are updating the array pass it in by reference as well.
void readFile(fstream& wordFile, string &words[], int &wordarrayLength)
{
int i=0;
while(i < MAX)
{
//each item in the array has to be it's own string
//the previous code simply reused the same string each time
string word;
getline(wordFile, word);
words[i] = word;
cout << words[i] << endl;
i++;
}
wordarrayLength = i;
wordFile.close();
}
Unfortunately I don't have your file or compiler so I can't debug it.

C++ passing strings causing segmentation fault

I am attempting to do a simple demographics input->output program. Enter persons information and it writes it to a csv file. However I can not get the name portion to work. I always get a segmentation fault. The code below is the offending bits and will not work. I know it has something to do with the strings, if I change to int it works just fine. All other data input(which has been remove for simplicity)works.
Main
#include <iostream>
#include "People.h"
using namespace std;
void demographics();
int main()
{
demographics();
return 0;
}
void demographics()
{
short elements = 2;
Names test[elements];
vector<string> name2;
for(int i =0; i<=elements; i++)
{
string name;
cout << "Please enter first name for child " << i+1 << endl;
cin >> name;
name2.push_back(name);
test[i].setName(name2);
}
return;
}
People.h
#ifndef PEOPLE_H_INCLUDED
#define PEOPLE_H_INCLUDED
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Names
{
private:
vector<string> names;
public:
void setName(vector<string>&);
};
People.cpp
#include "People.h"
#include <iostream>
using namespace std;
void Names::setName(vector<string>& f_l_name)
{
names = f_l_name;
}
for(int i =0; i<=elements; i++)
Should be
for(int i =0; i < elements; i++)

C++ test CIN on one line

I've recently started teaching myself C++, and after having written a lot of user input code, it's made me wonder if there's a simpler way of handling it.
For example, the normal way of doing it would be like this:
#include <iostream>
using namespace std;
int inp;
int guess = 13;
void main(){
cout << "Guess a number: ";
cin >> inp;
if (inp == guess)
cout << endl << "Nice.";
}
But what I want to do is:
#include <iostream>
using namespace std;
int guess = 13;
void main(){
cout << "Guess a number: ";
if (cin == guess)
cout << endl << "Even nicer.";
}
Is there a way to do this? Or this that just improper C++ standard?
In short: No, it's not possible to do as you want it.
You need to understand, that >> is actually a function call of
template<typename T>
std::istream& operator>>(std::istream& is, T& result);
and == is a function call to
template<typename T>
bool operator==(const std::istream&,const T& x);
Where the latter is used to check the stream state, and doesn't extract any user input.
To compare the input the result needs to be extracted from the std::istream in 1st place.
Well you can do it in one line but you don't really need to. But here are some examples anyway
//This will work for a char
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
char test = 'a';
if (getch()== test)
cout<<"\n Works";
return 0;
}
And if you really want
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int x =1;
int y;
for( cin >> y ; x == y ; )
{
cout<<"\n Works";
break;
}
return 0;
}
Or as NathanOliver said you could simply do this
if( cin >> inp && inp == guess )
But really you want to keep it simple as this will confuse others as well as yourself after some time. You want to leave your code as easy as possible