Heap corruption detected due to array usage - c++

Sorry, I'm a brand new newbie to C++ and programming and I'm getting a heap corruption error. I think Im writing in unallocated memory but I can't seem to find where the error is... the program is soppuse to take user input values and rearrange them so that they would ascend. I'm also learning templates too.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
template <typename T>
void sort(T arrayz[], int size, char ch)
{
T temporary;
int k, j;
if (ch = 'a')
{
for (k = 0; k < size; k++)
{
for (j = 0; j < size; j++)
{
temporary = arrayz[j];
arrayz[j] = arrayz[j + 1];
arrayz[j + 1] = temporary;
}
}
}
}
int main()
{
int choices, range, i;
int x;
char ch;
cout << ("Enter the amount of numbers you want =>");
cin >> x;
int *numbers = new int[x];
if (!numbers)
{
cout << "Memory Allocation error!";
cin.get();
exit(1);
}
for (int i = 0; i<x; i++)
{
cout << "Option number" << i + 1 << " =>";
cin >> numbers[i];
}
cout << "Do you want ascending or descending values (a/d) =>" ;
cin >> ch;
if (ch = 'a')
{
sort(numbers, x, ch);
}
else if (ch = 'd')
{
sort(numbers, x, ch);
}
delete[] numbers;
fflush(stdin);
cin.get();
return 0;
}

In your sort function, you are accessing elements at index j + 1. However, this is out of bounds. The valid indexes for your arrayz array are 0 through size-1. When j is size-1, j+1 is size, which accesses past the end of the array.

Related

C++ code Runtime error on 2D array declaration

I dont understand why is this code giving runtime error on input of any test case (size of string is n, and then string is input). Not even the word "CHECK" (in the solve() function) gets printed.. Please help!
The problem link is : problem
#include <bits/stdc++.h>
using namespace std;
int a[1000][26];
int mov(int l, int u, int x)
{
if(l==u)
{
if(a[l][x]-a[l-1][x]==1)
return 1;
else
return 0;
}
int m=(l+u)/2;
return max(mov(l,m,x+1)+a[u][x]-a[m][x],mov(m,u,x+1)+a[m][x]-a[l-1][x]);
}
void solve()
{
int i,k,j,n;
string str;
cin >> n >> str;
cout << "CHECK";// This is not getting printed
for(i=0;i<26;i++)
a[0][i]=0;
for(i=1;i<n+1;i++)
{
for(j=0;j<26;j++)
{
a[i][j]=a[i-1][j];
if(str[i-1]==j+'a')
a[i][j]++;
}
}
k=mov(1,n,0);
cout << n-k << "\n";
}
int main()
{
int t=1;
cin >> t;
while(t--)
solve();
}
Your very first input shows how many input "pairs" will be given. In your case, you have skipped this part and gone into gathering the input "pairs". This is why "CHECK" wont get printed. To resolve this, have a cin to capture the number of input pairs, then iterate through the inputs to get the pair.
void solve()
{
int i, k, j, n;
string str;
memset(a[0], 0, sizeof(int) * 26); // Use this instead.
cin >> n;
cout << "CHECK";
for (i = 1; i < n + 1; i++)
{
cin >> j >> str;
for (j = 0; j < 26; j++)
{
a[i][j] = a[i - 1][j];
if (str[i - 1] == j + 'a')
a[i][j]++;
}
}
k = mov(1, n, 0);
cout << k << "\n";
}
Also, try not to use using namespace std;.

Why is the Vector array printing the memory addresses instead of the array values and why do I get an access violation in my sorting functions? [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'm developing a program that reads text files and stores the words in an array that can be sorted and then searched through. I've already tried using a dynamically allocated array to place the words into from the text files, but all I get is string cannot be read error from my getline (this doesn't happen when I use vectors). When I try to print out the vector array to see what is being passed through to my sorting functions, it prints out the memory addresses of the array and not the values stored in the array.
I also get a read access violation in my sorting functions at certain points in the function after I've pass the vector arrays to them and I don't understand why. I do show in the code where the problem is accruing. Please note that I'm very new to coding and this program is far from complete. I'm including all of the code I have done so far because if I just show the problem areas I don't think it will be understandable why I'm having these errors. Any help is appreciated thank you.
#include "flore0900header.h"
int main()
{
string name;
int num = 0, num2 = 0, count = 0;
vector<string> word; //to pass vector array to another function
cout << "Hello. Enter your name: ";
cin >> name;
cout << endl;
cout << "Welcome " << name << " This program lets you test 5 different sorting algorithms using texts files" << endl;
cout << endl;
cout << "Which text file would you like to search?" << endl;
cout << "=========================================" << endl;
cout << "1. The Blue Hotel" << endl;
cout << "2. 20,000 Leagues Under the Sea" << endl;
cout << "3. A Tale of Two Cities" << endl;
cin >> num;
count = text_select(num);
catch_array(&word); //passing vector array by reference. '&' is there because it won't work otherwise
cout << endl;
cout << "Which sorting algorithems would you like to use?" << endl;
cout << "========================================" << endl;
cout << "1. Selection" << endl;
cout << "2. Bubble" << endl;
cout << "3. Insertion" << endl;
cout << "4. Merge" << endl;
cout << "5. Quick" << endl;
cin >> num; cin >> num2;
sort_select(num, &word, count);//'&' is there because it won't work otherwise
sort_select(num2, &word, count);//'&' is there because it won't work otherwise
cout << endl;
cout << "Ok! Running algorithms..........." << endl;
}
the header file
#ifndef FLORE0900HEADER_H
#define FLORE0900HEADER_H
#include <iomanip>
#include <ctime>
#include <cstdlib>
#include <istream>
#include <fstream>
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
#include <ostream>
/* some of the includes are not needed, I haven't removed the un-needed ones yet*/
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::vector;
void selection_sort(vector<string> a[], int size);
void bubble_sort(vector<string> a[], int size);
void insertion_sort(vector<string> a[], int size);
void merge_sort(vector<string> a[], int from, int to);
void quick_sort(vector<string> a[], int from, int to);
int text_select(int num);
void sort_select(int num, vector<string> a[], int size);
vector<string> catch_array(vector<string> a[]);
void merge(vector<string> a[], int from, int mid, int to);
int min_position(vector<string> a[], int from, int to);
int partition(vector<string> a[], int from, int to);
void swap(int& x, int& y);
void print(vector<string> a[], int size);
#endif
text_select function file
#include "flore0900header.h"
//#include <vector>
int text_select(int num)
{
int count = 0;
vector<string> words(100000);
//vector<string>* word2 = new vector<string>[count];
std::ifstream infile;
if (num == 1)
{
infile.open("blue_hotel.txt");
if (infile.is_open())
{
cout << "file is open" << endl;
getline(infile, words[count]);//string read error when using not using vector
while (!infile.eof())
{
infile >> words[count];
count++;
infile.ignore();
getline(infile, words[count]);
}
}
else
{
cout << "file didn't open" << endl;
exit(1);
}
}
else if (num == 2)
{
infile.open("2under.txt");
if (infile.is_open())
{
cout << "file is open" << endl;
getline(infile, words[count]);
while (!infile.eof())
{
infile >> words[count];
count++;
infile.ignore();
getline(infile, words[count]);
}
}
else
{
cout << "file didn't open" << endl;
exit(1);
}
}
else if (num == 3)
{
infile.open("2city10.txt");
if (infile.is_open())
{
cout << "file is open" << endl;
getline(infile, words[count]);
while (!infile.eof())
{
infile >> words[count];
count++;
infile.ignore();
getline(infile, words[count]);
}
}
else
{
cout << "file didn't open" << endl;
exit(1);
}
}
else
cout << "not a valid choice try again" << endl;
infile.close();
catch_array(&words);//if I don't use '&' the vector won't pass through
return count;
}
vector<string> catch_array(vector<string> a[])
{
return *a;//if I don't put '*' before the 'a' I get an error
}
sort_select file
#include "flore0900header.h"
void sort_select(int num, vector<string> a[], int size)
{
int from = 0;
if (num == 1)
{
selection_sort(a, size);
}
else if (num == 2)
{
bubble_sort(a, size);
}
else if (num == 3)
{
insertion_sort(a, size);
}
else if (num == 4)
{
merge_sort(a, from, size);
}
else if (num == 5)
{
quick_sort(a, from, size);
}
else
cout << "not a valid pick try again" << endl;
}
selection_sort file
#include "flore0900header.h"
void selection_sort(vector<string> a[], int size)
{
int next;
for (next = 0; next < size - 1; next++)
{
print(a, size);//to see what is being passed to the function
int min_pos = min_position(a, next, size - 1);
swap(a[next], a[min_pos]);
}
}
int min_position(vector<string> a[], int from, int to)
{
int min_pos = from;
for (int i = from + 1; i <= to; i++)
{
if (a[i] < a[min_pos])//read access violation happens here
{
min_pos = i;
}
}
return min_pos;
}
void print(vector<string> a[], int size)
{
for (int i = 0; i < size; i++)
{
cout << &a[i] << " ";//is printing memory locations instead of values
}
cout << endl;
}
bubble_sort file
#include "flore0900header.h"
void bubble_sort(vector<string> a[], int size)
{
for (int i = 0; i < size - 1; i++) //loop for recording no# of iteration needed to complete the sorting
{
int flagForSwap = 0; //creates a flag variable that accounts for wheather the swap function is called at all
//loop for counting comparisons
for (int j = 0; j < size - 1 - i; j++)
{
if (a[j] > a[j + 1]) //(read access violation happens here) compare adjacent array elements
{
swap(a[j], a[j + 1]); //completes the swap
flagForSwap = 1; // flag to 1 if swap is used
}
}
if (flagForSwap == 0) //breaks the iteration loop if inputed array is already sorted and no swap is needed
{
break;
}
}
}
void swap(int& x, int& y)
{
int temp = x; //creates a temp variable to store the value of the current element
x = y; // change the value of the current element to next element
y = temp; //assigns the value of temp to next element
}
insertion_sort file
#include "flore0900header.h"
void insertion_sort(vector<string> a[], int size)
{
for (int i = 1; i < size; i++)
{
vector<string> next = a[i];//read access violation happens here
int j = i;
while (j > 0 && a[j - 1] > next)
{
a[j] = a[j - 1];
j--;
}
a[j] = next;
}
}
merge_sort file
#include "flore0900header.h"
void merge_sort(vector<string> a[], int from, int to)
{
if (from == to)
{
return;
}
int mid = (from + to) / 2;
merge_sort(a, from, mid);
merge_sort(a, mid + 1, to);
merge(a, from, mid, to);
}
void merge(vector<string> a[], int from, int mid, int to)
{
int n = to - from + 1;
vector<string>* b = new vector<string>[n];
int i1 = from;
int i2 = mid + 1;
int j = 0;
while (i1 <= mid && i2 <= to)
{
if (a[i1] < a[i2])//read access violation happens here
{
b[j] = a[i1];
i1++;
}
else
{
b[j] = a[i2];
i2++;
}
j++;
}
while (i1 <= mid)
{
b[j] = a[i1];
i1++;
j++;
}
while (i2 <= to)
{
b[j] = a[i2];
i2++;
j++;
}
for (j = 0; j < n; j++)
{
a[from + j] = b[j];
}
delete[] b;
}
quick_sort file
#include "flore0900header.h"
void quick_sort(vector<string> a[], int from, int to)
{
if (from >= to)
{
return;
}
int p = partition(a, from, to);
quick_sort(a, from, p);
quick_sort(a, p + 1, to);
}
int partition(vector<string> a[], int from, int to)
{
vector<string> pivot = a[from];
int i = from - 1;
int j = to + 1;
while (i < j)
{
i++;
while (a[i] < pivot)//read access violation happens here
{
i++;
}
j--;
while (a[j] > pivot)
{
j--;
}
if (i < j)
{
swap(a[i], a[j]);
}
}
return j;
}
There is no such thing as "a vector array".
You can have arrays of vectors, but you don't.
Yet, here, your function is written as if it does:
int partition(vector<string> a[], int from, int to)
// ^^
I imagine this was done because, before you added the [] here and the & there, your functions appeared not to do anything.
That was because you were passing the vector by value, so changes in the function were made to a copy, and thus not reflected in the calling scope.
Your changes allowed the code to compile, and possibly even "work" in some obscure cases, but only by chance; the [INDEX] syntax is shared between vectors and arrays. But you don't have an array, so pretending to the function that you do is wrong. Most of your accesses go out of bounds.
Also note that if you didn't have a bool operator<(const vector<string>&, const vector<string>&) defined somewhere, it wouldn't compile.
Anyway, the solution to use your one vector is simple:
Get rid of that []
Get rid of that &
Change what is now vector<string> into vector<string>&. That & means "take a reference".

how to create an array of Bitset in c++

I want to create an array of Bitset .Binary Bitset(example "100","1010",etc)
After that I want to input from user and store in the the Bitset .
I have tried the following line but it says error.
#include<bits/stdc++>
using namespace std;
int main()
{
int n,i;
string bit_string;
cin>>n // size of Bitset array.
bitset<8> brr[n];//
for(i=0;i<n;i++)
{
cin>>bit_string;
brr[i](bit_string);
}
return 0;
}
I want to create n Bitset each of size 8 bits.Where n is given by user.
my input is binary string like.
"110010","001110"
please help
The error ocurrs because you are trying to creat a C-style array using n which is not compile-time constant. It's not possible to creat a C-style array without being n known at compile time.
The following is a good way to do what you want
Creat a std::vector<std::bitset<8>> to hold your bitset<8>s, as follows.
Note that the code ignores the excess of characters in strings iput like "111111110" (makes it "11111111") and treats any character except '1' as if it were '0' and if the input string is less than 8 characters, the code adds zeros by the default of the bitsets
#include <vector>
#include <bitset>
#include <iostream>
int main() {
int n, i;
std::string bit_string;
std::cout << "Enter the size";
std::cin >> n; // size of Bitset array.
std::vector<std::bitset<8>> brr(n);//
for (i = 0; i < n; i++) {
std::cin >> bit_string;
for (int j{}; j < bit_string.size() && j < 8; ++j) {
brr[i][j] = (bit_string[j] == '1') ? 1 : 0;
}
}
//To test
for(auto const& el :brr)
{
for(int i{}; i < 8;)
std::cout << el[i++];
std::cout<<"\n";
}
}
See Why is "using namespace std;" considered bad practice?
and
Why should I not #include <bits/stdc++.h>?
For dynamic count of the objects , Please try vector<> instead of array[]
#include<bits/stdc++>
using namespace std;
int main()
{
int n, i;
string bit_string;
cin >> n; // size of Bitset array.
vector<bitset<8>> arr; //size()=>0
arr.resize(n); //size()=>n
for (i = 0; i < n; i++)
{
cin >> bit_string;
bitset<8>& br = arr[i]; //get the i of n
int maxlen = 8;
if (bit_string.size() <= 8)
maxlen = bit_string.size();
else
cout << "warning invalid len " << bit_string.size() << " of " << bit_string << endl;
for (int j = 0; j < maxlen; j++)
{
if (bit_string[j] == '1')
br.set(j, true);
}
//cout << endl << br << endl; //output test
}
return 0;
}
If you still want to use array , please try this way
#include<bits/stdc++>
using namespace std;
int main()
{
int n, i;
string bit_string;
cin >> n; // size of Bitset array.
bitset<8>* arr = new bitset<8>[n];
for (i = 0; i < n; i++)
{
cin >> bit_string;
bitset<8>& br = arr[i]; //get the i of n
int maxlen = 8;
if (bit_string.size() <= 8)
maxlen = bit_string.size();
else
cout << "warning invalid len " << bit_string.size() << " of " << bit_string << endl;
for (int j = 0; j < maxlen; j++)
{
if (bit_string[j] == '1')
br.set(j, true);
}
//cout << endl << br << endl; //output test
}
delete[] arr; //IMPROTAND , delete the array and free memory
return 0;
}

Can someone help to find the reason for s runtime error in this code?

The code runs fine in my compiler but shows runtime error on codeforces. I found out that I should avoid unitialized variables but I think I've already covered that.
#include <iostream>
using namespace std;
int main()
{
int i, n, flag = 1, k = 1;
int hours[n];
int minutes[n];
cin >> n;
for (i = 0; i < n; i++)
{
cin >> hours[i];
cin >> minutes[i];
}
for (i = 0; i < n; i++)
{
if (hours[i] == hours[i + 1] && minutes[i] == minutes[i + 1])
{
flag++;
if (flag > k)
k = flag;
}
else
flag = 1;
}
cout << k;
return 0;
}
The problem lies here
int i, n, flag = 1, k = 1;
int hours[n];
int minutes[n];
You declare variables n, but you don't initialize it, and then you use it to specify an array size. Uninitialized variables of type int contain garbage data, and using it is undefined behavior, whatever happens is unspecified, and you can not rely on it.
If you must create an array of size specified by a user input, you need to allocate at runtime.
int *hours;
int *minutes;
cin >> n;
hours = new int[n];
minutes = new int[n];
// Rest of the code
// Remember to delete them
delete[] minutes;
delete[] hours;
Better yet, use a container provided by the standard library, a std::vector would be a perfect container to use here
#include <vector>
std::vector<int> hours;
std::vector<int> minutes;
cin >> n
hours.resize(n);
minutes.resize(n);
VLAs are not standard C++ but are allowed as an extension. The first problem in your code is that you use the variable n without initialization. This causes undefined behavior according to the standard.
You need to move the call to cin() to above the arrays that use n at declaration. The second problem in your code is that the expression inside the if statement attempts to access an element outside the bounds of your array. This also causes undefined behavior.
Here is a refined version of your code:
#include <iostream>
using namespace std;
int main()
{
int n;
int k = 1;
int flag = 1;
cout << "Enter a value for n:" << endl;
cin >> n;
int *hours = new int[n];
int *minutes = new int[n];
cout << "Enter values for hours:" << endl;
for (int i = 0; i < n; i++)
{
cout << i + 1 << ":";
cin >> hours[i];
}
cout << "Enter values for minutes:" << endl;
for (int i = 0; i < n; i++)
{
cout << i + 1 << ":";
cin >> minutes[i];
}
// note here: 'i' goes to (n - 1) instead of (n) so as not to be out of range
for (int i = 0; i < n - 1; i++)
{
if ((hours[i] == hours[i + 1]) && (minutes[i] == minutes[i + 1]))
{
flag++;
if (flag > k)
{
k = flag;
}
}
else
{
flag = 1;
}
}
cout << "The value of k is: " << k << endl;
delete hours;
delete minutes;
return 0;
}

How the assigned value to variable gets changed automatically?

When I am providing input for std::cin >> diff; it takes the input value, and the moment I am entering the value of array, the diff variables value gets changed and sets the value of 4th element of the array.
Please help me where is it going wrong. I have tried with fflush(std). But it did not help me.
I am using Visual Studio 2010 Ultimate edition.
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int i, num;//[]={0};
int diff = 0;
int numset[] = {0};
int temp, cnt;
cnt = num = i = 0;
std::cout << "Enter your number and difference : ";
//fflush(stdin);
std::cin >> num ;
std::cin >> diff;
cout << "Enter array Elements : \n";
for(i = 0; i < num; i++)
{
cin >> numset[i];
//fflush(stdin);
}
for(i = 0; i < num; i++)
{
for(int j = i; j < num; j++)
{
if(i == j)
{
temp = numset[j];
}
else
{
if((diff == (numset[j] - temp)) || (((-1)*diff) == (numset[j] - temp)))
{
cnt++;
}
}
}
}
cout << cnt << endl;
system("pause");
return 0;
}
You're accessing beyond the bounds of the array numset, so your code has Undefined Behaviour (UB) and anything could happen. It could overwrite variables on stack (as it does in your case), it could crash, it could order pizza online.
numset is declared as a single-element array, so accessing numset[i] for i > 0 results in UB. You should probably change numset to be a std::vector<int> and use push_back() to append numbers to it.