Keep getting Segmentation Fault : 11 message in C++? - c++

The assignment is to search for a word inside a matrix (only left to right) by putting the word and starting point in the command line and return true if the word is there and false if it is not. Unfortunately, I continue to recieve a segmentation fault msg. Any help is greatly appreciated, thanks!
#include <iostream>
#include <vector>
#include <sstream>
#include <string>
using namespace std;
int main(int argc, char *argv[]){
for(int i = 0; i < argc; i++){
cout << argv[i] << " ";
}
char word;
argv[1] = &word;
stringstream ss;
string sWord;
ss << word;
ss >> sWord;
int startRow = atoi(argv[2]);
int startCol = atoi(argv[3]);
int x, y;
cin >> x >> y;
cout << x << y << endl;
vector < vector < char > > matrix;
matrix.resize(x);
for(int i = 0; i < matrix.size(); i++){
matrix.resize(y);
for(int k = 0; k < matrix.size(); k++){
cin >> matrix[i][k];
}
}
for(int i = 0; i < strlen(argv[1]); i++){
if(matrix[startRow][startCol + i] != sWord[i]){
return false;
}
else{
return true;
}
}
}

You are calling strlen() on the address of a single char:
char word;
argv[1] = &word;
...
for(int i = 0; i < strlen(argv[1]); i++){
strlen() requires a null-terminated array of chars, since it only stops at the null-terminator '\0'.
Since the variable "word" is never actually set to anything, your char variable will not have a null-terminator, so strlen() will continue until it reaches a '\0' in memory, which in this case, seems to run beyond your program stack ("word" is a local stack variable, so its address points to your program stack).
I am not sure why you are assigning argv[1] to the address of a char variable, but this should answer your question on why your program is terminating unexpectedly.

You are not initializing your matrix properly:
Instead of
for (int i = 0; i < matrix.size(); i++) {
matrix.resize(y);
your probably meant to write
for (int i = 0; i < matrix.size(); i++) {
matrix[i].resize(y); //resizze "inner" vector

Related

C++ replacing values in a dynamic 2D Array

I'm trying to replace the '.' in my array with 'O'but it inserts it in between rather than taking its place. Please help I don't know what I'm doing wrong.
#include <iostream>
using namespace std;
char** createField(int w, int l)
{
int obstacles;
char ** arr = new char * [w];
for(int i=0; i<w; i++)
{
arr[i] = new char[l];
}
//Initializing the values
for(int i = 0; i < w; ++i)
{
for(int j = 0; j < l; ++j)
{
arr[i][j] = 0;
}
}
cout<<"Enter number of obstacles: ";
cin>>obstacles;
int x=0;
int y=0;
for (int j = 0; j < obstacles; ++j) {
cout<<"Enter location of obstacles: ";
cin>>x>>y;
arr[x][y] ='O';
}
for(int i = 0; i < w; ++i)
{
for(int j = 0; j < l; ++j)
{
if(i==0 || i == w-1){
cout<< arr[i][j]<< 'W';
}else if(j==0 || j==l-1){
cout<< arr[i][j]<< 'W';
} else
cout<< arr[i][j]<< '.';
}
cout<<"\n";
}
return arr;
}
int main() {
int w;
int l;
cout << "Enter the Width: ";
cin >> w;
cout << "Enter the length: ";
cin >> l;
//Pointer returned is stores in p
char **p = createField(w, l);
//Do not Forget to delete the memory allocated.It can cause a memory leak.
for (int del = 0; del < w; del++) {
delete[] p[del];
}
delete[]p;
}
Here is an example of my output, I want the 'O' to replace the '.' rather than be in between the two. Also if someone could explain why this is happening that would be really helpful Thanks.
Example of output: w.O.w
Desired output: w.Ow
When you set arr[i][j] = 0, it will cast 0 into char before assigning it to arr[i][j]. 0 casts to the literal '\0' which means a null character. Later when you print the contents of arr, the null characters cannot be seen in output which is part of the underlying cause of your confusion. Hope that explains what's going on a little bit better.

Trouble with segmentation faults in 3D array

I'm having trouble getting rid of the core segmentation fault on this code. It's creating a series of names in a 3-dimensional array with the dimensions row, col, and chars, where chars stores up to 5 letters of a name.
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
const int MAXSIZE = 11;
char*** names;
names = new char** [MAXSIZE];
cout << &names << " ";
for (int i = 0; i < MAXSIZE; ++i) {
names[i] = new char* [MAXSIZE];
cout << &names[i] << " ";
for (int j = 0; j < MAXSIZE; ++j) {
names[i][j] = new char [5];
cout << &names[i] << " " << i << j;
}
cout << endl;
}
I've inserted some debugging in there too. I see that it is able to finish assigning addresses, so I'm not sure what's going wrong. No other code is being done, even as I have deletes at the end that are all good.
Your code is ok, but remember that you can only store 4-symbol names in char[5] array.
Some modifications of your example
const int MAXSIZE = 11;
char*** func()
{
char*** names;
names = new char**[MAXSIZE];
for(int i = 0; i < MAXSIZE; ++i)
{
names[i] = new char*[MAXSIZE];
for(int j = 0; j < MAXSIZE; ++j)
{
names[i][j] = new char[5];
memset(names[i][j], 0, 5);
memcpy(names[i][j], "abcd", 4); // !!! only 4 symbols for name !!!
}
}
return names;
}
int main()
{
char ***names = func();
for(int i = 0;i < MAXSIZE;i++)
for(int j = 0;j < MAXSIZE;j++)
cout << names[i][j]<< endl;
// free memory
}

How to not get end of line character using cin.get() in c++

so I know how to use cin.get() and how to use buffers or so I thought. Here is a sample program which gets n(number or rows) and m(number of columns) for a table. Then it gets n*m characters, saves them in an array and outputs them:
#include <bits/stdc++.h>
using namespace std;
int n, m;
char in;
char a[100][100];
int main()
{
cin >> n >> m;
for(int i = 0;i < n; ++i)
{
for(int j = 0;j < m; ++j)
{
cin.get(in);
a[i][j] = in;
if(j == m - 1)
cin.get();
}
}
for(int i = 0;i < n; ++i)
{
for(int j = 0;j < m; ++j)
cout <<a[i][j];
cout << endl;
}
return 0;
}
This program seems to count some chars as end of lines. Can someone fix that and explain me. Thank you in advance!
When you enter n and m, cin.get() will start immediately at the char following the number, which could be a space or a new line. There might therefore be a shift between the input you expect and the input that you get. This causes every m chars to be ignored ieven if not a newline, and converseky, some newlines to be read instead of another char.
After your number extraction, it would be safer to cin.ignore() chars until the first new line.
Similarly, check for every nth char that you skip, if it is the newline that you expect.
You have to use cin if you do not want endl and space characters;
Just replace cin.get() with cin>>
#include <bits/stdc++.h>
using namespace std;
int n, m;
char in;
char a[100][100];
int main()
{
cin >> n >> m;
for(int i = 0;i < n; ++i)
{
for(int j = 0;j < m; ++j)
{
cin>>in;
a[i][j] = in;
}
}
for(int i = 0;i < n; ++i)
{
for(int j = 0;j < m; ++j)
cout <<a[i][j];
cout << endl;
}
return 0;
}

Scanning char array and putting it in struct properly in c++

Wanted to get my char array to be in a struct, but it crashes.
As I realised after, there is also a problem when scanning the array.
The input string consists of two words, name and surname, separated by a space. I haven't yet written the part where it scans the second word, so now it scans only the first.
The check lines in code have s weird output. I input "James" and it gives me "J8224a8224m8224e8224s8224" and then crashes.
#include <iostream>
#include<string.h>
using namespace std;
struct base
{
char* name;
char* surname;
int point1;
int point2;
};
main()
{
setlocale(LC_ALL, "rus");
int n;
cin >> n;
base a[n];
char symb;
char sym[20];
int j = 0;
for (int i = 0; i < n; i++)
{
do
{
symb = getchar();
sym[j] = symb;
j++;
} while (symb != ' ');
for (int k = 0; k < j; k++) //check
cout << sym[k] << ' '; //check
strcpy(sym, a[i].name);
j = 0;
}
}
There are several errors:
You cannot use static initialization for base a[n], because variable n is not known while compiling.
You have to initialize a[i].name before you do strcpy.
You shlould use sptncpy instead of strcpy if you know lenght which is j.
You code should look like this
int main()
{
setlocale(LC_ALL, "rus");
int n;
cin >> n;
base *a = new base[n];
char symb;
char sym[20];
int j = 0;
for (int i = 0; i<n; i++)
{
do
{
symb = getchar();
sym[j] = symb;
j++;
} while (symb != ' ');
for (int k = 0; k<j; k++) //check
cout << sym[k] << ' '; //check
a[i].name = new char[j];
strncpy(sym, a[i].name, j);
j = 0;
}
}

User defined matrix of chars

From user input such as:
>~d
alg
^%r
what would be the best way to create a square char matrix with each of the entered values assigned to the corresponding element? e.g. in this case charArray[0][0] would be '>' and charArray[2][1] would be '%' etc.
I tried the following using getchar(); however, I was having all kinds of problems with the '\n' that was left behind and figured there is probably an entirely different way of effecting this that was much better.
char matrix[MAX][MAX];
char c;
int matSize;
std::cin >> matSize;
for (int i = 0; i < matSize; ++i)
{
int j = 0;
while ((c = getchar()) != '\n')
{
matrix[i][j] = c;
++j;
}
}
As you're using C++, why not use std::cin and std::string to read a hole line. Probably not the best option, but it works.
for (int i = 0; i < matSize; ++i)
{
std::cin >> in;
if (in.length() < matSize)
{
printf("Wrong length\n");
return 1;
}
for (int j = 0; j < matSize; j++)
matrix[i][j] = in[j];
}
Since every matrix[i] is a char array with a fixed size you can easily use std::istream::getline:
#include <iostream>
#include <istream>
#define MAX 10
int main()
{
char matrix[MAX][MAX];
char c;
int matSize;
std::cin >> matSize;
std::cin >> c; // don't forget to extract the first '\n'
if(matSize > MAX){ // prevent segmentation faults / buffer overflows
std::cerr << "Unsupported maximum matrix size" << std::endl;
return 1;
}
for(int i = 0; i < matSize; ++i){
std::cin.getline(matrix[i],MAX); // extract a line into your matrix
}
std::cout << std::endl;
for(int i = 0; i < matSize; ++i){
std::cout << matrix[i] << std::endl;
}
return 0;
}