Sample program crashes - c++

I'm trying to make a program where the user inputs the "shape" by adding characters such as *,/ etc. and then print it on the screen the amount of times the user inputs. The program works fine but in the end it says program not responding. Any help with that?
#include <iostream>
using namespace std;
int main()
{
int a,h=1 ,b=0, x=7;
char test[a][100];
cout<<"Input how many lines ";
cin>>a;
cout<<"Input how many repeats ";
cin>>b;
for(int j=1; j<=a; j++)
{
cin>>test[j];
}
while(h<=b)
{
for(int c=1; c<=a; c++)
{
cout<<test[c]<<"\n";
}
h++;
}
return 0;
}

Your code invokes Undefined Behaviour (UB) here:
int a, ...;
char test[a][100];
You are trying to declare a fixed-size 2D array with an uninitialized variable (a).
Moreover, even if it was, variable-sized arrays are not standard C++.
If you enable the warning flags (such as Wall in GCC), you should get:
prog.cc:7:21: warning: 'a' is used uninitialized in this function [-Wuninitialized]
char test[a][100];
^
Moreover, array indexing starts from 0 and ends at the N - 1, where N is the size of the array. So you need to change this:
for(int j=1; j<=a; j++)
to this:
for(int j=0; j<a; j++)
in order to access the array right, and not out bounds as it happens when j gets the value of a. Accessing an array out of bounds causes Undefined Behaviour as well.

Related

why I am getting i at the end of char array?

#include<iostream>
#include<string.h>
using namespace std;
int main() {
int n;
cin>>n;
char code[n];
cin.ignore();
cin.getline(code, n);
int j=0;
for(int i=0; i<n; i++) {
if((code[i]>='A' && code[i]<='Z') || (code[i]>='a' && code[i]<='z')) {
code[j] = code[i];
j++;
}
}
code[j] = '\0';
cout<<code;
return 0;
}
input :
10
Ajith##
Expected output :
Ajith
Acutal output I'm getting :
Ajithi
why I am getting i at end of array ?
I need to print only alphabets ignoring numbers and special symbols. please help me on this
You tell the program that the input will be ten characters, including null-terminator.
Then you input only seven characters. With the null-terminator that leaves two uninitialized elements of the array, and those two elements will have indeterminate values.
Your loop still uses all ten characters, and using indeterminate values in any way leads to undefined behavior.
What is likely happening is that there's some data after the null-terminator that your program believes is characters.
The solution is std::string and only iterating over the actual length of the string, copying to another std::string.

Getting Segmentation Fault error in C++ code

#include<bits/stdc++.h>
using namespace std;
//FIRST REPEATING ELEMENT (APPROACH 2)
int main()
{
cout<<"running";
int n;
cin>>n;
int arr[n];
for(int i=1; i<=n; i++)
cin>>arr[i];
const int N = 1e5+2;
int idx[N];
for(int i=0;i<N;i++)
idx[i] = -1;
int minidx = INT_MAX;
for(int i=0;i<n;i++)
{
if(idx[arr[i]] != -1)
minidx = min(minidx, idx[arr[i]]);
else
idx[arr[i]] = i;
}
if(minidx == INT_MAX)
cout<<"-1"<<endl;
else
cout<<minidx + 1<<endl;
return 0;
}
I am writing this code for "First Repeating Element" question and trying to get the index of the first element that repeats.
On debugging, I am getting segmentation fault.
int main()
{ (in this line)
What does it mean and what can I do to remove this.
const int N = 1e5+2;
int idx[N];
That sounds like a big array to be allocated on the stack (400kb!). Try using malloc() to allocate an array of that size. Change that to something like
const int N = 1e5+2;
int* idx = (int*)malloc(N * sizeof(int));
You should also do the same for arr, particularly if you use large values for n.
The program has undefined behavior because you're going out of bound of the array. This is because in your for loop condition, you're using i<=n instead of i<n.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior. The program may just crash.
So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash.
So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.
Additionally, in Standard C++ the size of an array must be a compile time constant. This means that the following is incorrect in your program.
int n;
cin >> n;
int arr[n]; //not standard C++ since n is not a constant expression
1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.
Segmentation fault is due to usage of memory that you don't own, or in other words stack over flow. Most likely because you're creating an array of size 1e5+2 and looping over it, initializing every element. That's not the best way to find the recurrence of an element. Instead use a map with key value pairs.

C++- Filling a 2D array from user input

I'm new to programming and was finding transpose of a matrix.
However, I want the input of the matrix from the user and by writing the following code, the complier doesn't take any input values and immediately stops.
I looked into previous questions posted here about the same but found non useful.
#include<iostream>
using namespace std;
int main()
{
int rows,val;
int num[rows][rows];
cin>> rows;
for(int i=1; i<= rows; i++)
{
for(int j = 1; j <= rows; j++)
{
cin>> val;
arr[i][j]= val;
}
cout<<endl;
}
You can't use variables in array length if they aren't defined as one of the comments mentioned.
arr[i][j] inside your nested for loop isn't declared so that would also give an error, I guess you wanted to use num array which you declared.
The rest is all looking good

Error in code while using logical operator '&&' several times in c++

I have done Following code to count X in an array. Here the compliation error which i get.
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
char s [n][n] ;
cin>>n;
char c ;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin >> c ;
if(c=='X')
{
s[i][j]='X';
}
}
}
int count=0;
for(int i=1;i<n-1;i++)
{
for(int j=1;j<n-1;j++)
{
if( s[i][j]=='X' && s[i−1][j−1] =='X' && s[i−1][j+1]=='X'&& s[i+1][j−1] =='X' && s[i+1][j+1] =='X')
count++;
}
}
cout<<count<<endl;
return 0;
}
prog.cpp: In function ‘int main()’:
prog.cpp:23:34: error: expected ‘:’ before ‘]’ token
{ if( s[i][j]=='X' && s[i?1][j?1] =='X' && s[i?1][j+1]=='X'&& s[i+1][j?1] =='X' && s[i+1][j+1] =='X')
^
There's nothing wrong with the logical ANDs in the if-statement - well, apart from being unreadable. The problem is everywhere else tbh.
using namespace std;
Try to avoid using namespaces like that. This is so that you prevent ambiguity with name collisions.
char s[n][n];
This is not valid C++. It is known as a VLA. Read more about this in this answer here. Instead, use constexpr or a dynamic array such as std::vector.
int n;
char s[n][n];
cin>>n;
Due to the fact that n is a local variable, it is defined using garbage values (193446 or -539646 or ...). This means that you may end up with a 2D array of negative spaces??? It's only after that n is being set to a number from the user input. Assuming that VLAs are not a problem, what you should do is the following:
int n = 0;
cin>>n;
char s[n][n]; //still not valid C++
Furthermore, the 2D array is initialized with garbage values.
This, I have to admit, I do not understand. If the elements of the 2D array are only set when the user input is 'X', then what values will the rest of the array have?
cin >> c ;
if(c=='X')
{
s[i][j]='X';
}
Did you just want to fill in the array with user input values? If so, then all you need is the following:
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
std::cin >> s[i][j];
And finally the program counts the X patterns where X needs to be at all four corners of another X. Apart from the fact that having long if-statements is a bad practise, the if-statement would return the correct result.
See a running version of your demo here: https://rextester.com/ASQ26945

2D array elements not being read properly

The output is a string of numbers of entire row/column instead of a single number. Can someone please help me in this?
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int t;
cin>>t;
while(t--){
int n,m,cnt=0;
cin>>n>>m;
for(int i=0;i<=n+1;i++){
for(int j=0;j<=m+1;j++){
if(i==0||i==n+1||j==m+1||j==0) G[i][j]=0;
cin>>G[i][j];
}
}
cout<<G[1][2]<<endl;//this gives wrong o/p
return 0;
}
Most likely you are reading out of bounds due to a i <= n + 1 and j <= m + 1 conditions in your for loops thus invoking undefined behavior resulting in a corrupted stack which explains the output you are seeing. Modify the boundaries to:
i < n and j < m. Arrays are zero indexed in C++. First array element is accessed via somearray[0] and the last element is somearray[n-1] not somearray[n] which is what you are trying to access in your code. The same goes for multi-dimensional arrays. The statement of:
cout << G[i][j] << endl;
is wrongly placed outside the for loops. It should be inside the inner for loop. The array should be defined as a second statement in your while loop:
int G[n][m]; // Avoid VLAs
That being said variable length arrays are not part of the C++ standard and you should prefer std::vector and std::array to raw arrays.
Assuming G is a 2D array of size n x m, then you go out of bounds here:
for(int i=0;i<=n+1;i++) {
for(int j=0;j<=m+1;j++)
since array indexing starts from 0, and ends at size - 1.
As a result, your code invokes Undefined Behavior. To avoid that, simply change your double for loop to this:
for(int i = 0; i < n; i++) {
for(int j = 0;j < m; j++)