Data Management Error C++ - c++

I am having difficulties with my code. The issue is that even though my program runs all the way through, it still crashes at the end. My IDE gives me no disapproval and there is no indicator as to why my program is failing right at the end, so I am led to believe there is something going out of bounds or something messing up my stack. I have looked through my code and nothing appears to be out of bounds, so I am entirely confused on this matter.
I am using a header file I created, a file to contain my functions from the header file, and a main method file. The error is a result of the file containing my functions.
The fields of my class are
size - int
low - int
high - int
windowSize - int
*filteredArray - int
array[] - int
Here is the header file:
#ifndef FILTER_HPP_
#define FILTER_HPP_
#include<iostream>
class Filter {
int size;
int high;
int low;
int windowSize;
int *filteredArray;
int array[];
public:
// Constructor
Filter(int windowSize);
// Methods
void randArrayGen();
int* randArrayGenRecurHelper(int arrayRecur[], int count);
void randArrayGenRecur();
void printArrays();
int hanning(int ar[]);
void hanningFilter();
void graphicArrays();
int getSize();
int getHigh();
int getLow();
};
#endif /* FILTER_HPP_ */
Here is the code:
#include "Filter.hpp"
#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <cmath>
#include <array>
#include <string>
#include <cstring>
using namespace std;
// Constructor
Filter::Filter(int num){
size = ((rand() % 25) + 25);
high = ((rand() % 6) + 5);
low = ((rand() % 6) + 5) * -1;
windowSize = num;
randArrayGen();
hanningFilter();
}
void Filter::randArrayGen(){
for(int i = 0; i < size;i++){
array[i] = (rand() % (high + low * -1)) + low;
}
}
int Filter::hanning(int ar[]){
int weightAvg;
if(windowSize == 3){
weightAvg = (ar[0] + ar[1] * 2 +ar[2]) / 4;
}
else if(windowSize == 5){
weightAvg = (ar[0] + ar[1] * 2 + ar[2] * 3 + ar[3] * 2 + ar[4]) / 9;
}
else if(windowSize == 7){
weightAvg = (ar[0] + ar[1] * 2 + ar[2] * 3 + ar[3] * 4 + ar[4] *3 + ar[5] * 2 + ar[6]) / 16;
}
else if(windowSize == 9){
weightAvg = (ar[0] + ar[1] * 2 +ar[2] * 3 + ar[3] * 4 + ar[4] * 5 + ar[5] * 4 + ar[6] * 3 + ar[7] * 2 + ar[8]) / 25;
}
else{
weightAvg = 0;
}
return weightAvg;
}
void Filter::hanningFilter(){
filteredArray = new int[size];
for(int i = 0; i < size; i++){
if(i - (windowSize/2) < 0 or i + (windowSize/2) > size - 1){
filteredArray[i] = 0;
}
else{
filteredArray[i] = hanning(&array[i-(windowSize/2)]);
}
}
}
int Filter::getHigh(){
return high;
}
int Filter::getLow(){
return low;
}
int Filter::getSize(){
return size;
}

You don't allocate memory for your array:
int array[];
And when you index it like:
for(int i = 0; i < size;i++){
array[i] = (rand() % (high + low * -1)) + low;
}
you invoke Undefined Behavior, since you go out of bounds (you request the first element for example, but from an array of unknown size).
You could declare the array with a fixed size, like this for example:
int array[100];
However, since this is C++, consider using std::vector. An immediate advantage is that you don't have to hardcode a size for your statically allocated array, but you can rely on the vector's ability to resize as the data are inserted/pushed into it.

Related

A Program to Find Absolute Euler Pseudoprimes

I am now trying to make a program to find the Absolute Euler Pseudoprimes ('AEPSP' in short, not Euler-Jacobi Pseudoprimes), with the definition that n is an AEPSP if
a(n-1)/2 ≡ ±1 (mod n)
for all positive integers a satisfying that the GCD of a and n is 1.
I used a C++ code to generate AEPSPs, which is based on a code to generate Carmichael numbers:
#include <iostream>
#include <cmath>
#include <algorithm>
#include <numeric>
using namespace std;
unsigned int bm(unsigned int a, unsigned int n, unsigned int p){
unsigned long long b;
switch (n) {
case 0:
return 1;
case 1:
return a % p;
default:
b = bm(a,n/2,p);
b = (b*b) % p;
if (n % 2 == 1) b = (b*a) % p;
return b;
}
}
int numc(unsigned int n){
int a, s;
int found = 0;
if (n % 2 == 0) return 0;
s = sqrt(n);
a = 2;
while (a < n) {
if (a > s && !found) {
return 0;
}
if (gcd(a, n) > 1) {
found = 1;
}
else {
if (bm(a, (n-1)/2, n) != 1) {
return 0;
}
}
a++;
}
return 1;
}
int main(void) {
unsigned int n;
for (n = 3; n < 1e9; n += 2){
if (numc(n)) printf("%u\n",n);
}
return 0;
}
Yet, the program is very slow. It generates AEPSPs up to 1.5e6 in 20 minutes. Does anyone have any ideas on optimizing the program?
Any help is most appreciated. :)
I've come up with a different algorithm, based on sieving for primes upfront while simultaneously marking off non-squarefree numbers. I've applied a few optimizations to pack the information into memory a bit tighter, to help with cache-friendliness as well. Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#define PRIME_BIT (1UL << 31)
#define SQUARE_BIT (1UL << 30)
#define FACTOR_MASK (SQUARE_BIT - 1)
void sieve(uint64_t size, uint32_t *buffer) {
for (uint64_t i = 3; i * i < size; i += 2) {
if (buffer[i/2] & PRIME_BIT) {
for (uint64_t j = i * i; j < size; j += 2 * i) {
buffer[j/2] &= SQUARE_BIT;
buffer[j/2] |= i;
}
for (uint64_t j = i * i; j < size; j += 2 * i * i) {
buffer[j/2] |= SQUARE_BIT;
}
}
}
}
int main(int argc, char **argv) {
if (argc < 2) {
printf("Usage: prog LIMIT\n");
return 1;
}
uint64_t size = atoi(argv[1]);
uint32_t *buffer = malloc(size * sizeof(uint32_t) / 2);
memset(buffer, 0x80, size * sizeof(uint32_t) / 2);
sieve(size, buffer);
for (uint64_t i = 5; i < size; i += 4) {
if (buffer[i/2] & PRIME_BIT)
continue;
if (buffer[i/2] & SQUARE_BIT)
continue;
uint64_t num = i;
uint64_t factor;
while (num > 1) {
if (buffer[num/2] & PRIME_BIT)
factor = num;
else
factor = buffer[num/2] & FACTOR_MASK;
if ((i / 2) % (factor - 1) != 0) {
break;
}
num /= factor;
}
if (num == 1)
printf("Found pseudo-prime: %ld\n", i);
}
}
This produces the pseudo-primes up to 1.5e6 in about 8ms on my machine, and for 2e9 it takes 1.8sec.
The time complexity of the solution is O(n log n) - the sieve is O(n log n), and for each number we either do constant time checks or do a divisibility test for each of its factors, which there are at most log n. So, the main loop is also O(n log n), resulting in O(n log n) overall.

How to get a subset from maximum size subset with given sum solution [C]

I need to find a maximum size subset from a set of numbers which will have a given sum X.
I've found a solution which solves this:
// A Dynamic Programming solution for the
// subset sum problem+ maximal subset size.
#include <bits/stdc++.h>
using namespace std;
// Returns size of maximum sized subset
// if there is a subset of set[] with sum
// equal to given sum. It returns -1 if there
// is no subset with given sum.
int isSubsetSum(int set[], int n, int sum)
{
// The value of subset[i][j] will be true if there
// is a subset of set[0..j-1] with sum equal to i
bool subset[sum + 1][n + 1];
int count[sum + 1][n + 1];
// If sum is 0, then answer is true
for (int i = 0; i <= n; i++)
{
subset[0][i] = true;
count[0][i] = 0;
}
// If sum is not 0 and set is empty,
// then answer is false
for (int i = 1; i <= sum; i++)
{
subset[i][0] = false;
count[i][0] = -1;
}
// Fill the subset table in bottom up manner
for (int i = 1; i <= sum; i++)
{
for (int j = 1; j <= n; j++)
{
subset[i][j] = subset[i][j - 1];
count[i][j] = count[i][j - 1];
if (i >= set[j - 1])
{
subset[i][j] = subset[i][j] ||
subset[i - set[j - 1]][j - 1];
if (subset[i][j])
count[i][j] = max(count[i][j - 1],
count[i - set[j - 1]][j - 1] + 1);
}
}
}
return count[sum][n];
}
// Driver code
int main()
{
int set[] = { 2, 3, 5, 10 };
int sum = 20;
int n = 4;
cout << isSubsetSum(set, n, sum);
}
However that solutions provided output is maximum number of elements from the set that sum up to given sum X. I would also need to have the subset as well.
For example:
set[] = { 2, 3, 5, 7, 10, 15 }
sum = 10
The output will be 3 which is correct, but I would also know the subset which in this case would be {2, 3, 5}.
It is not obvious for me how to extract this as I don't fully understand the algorithm. I am working on C implementation, but if anyone can explain the algorithm then that would also help.
EDIT:
I've worked up some solution in standard C which works, but seems to have some problem.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct s_set {
int indx;
int arr[15];
};
int main(int argc, char *argv[]) {
int set[] = {2, 3, 5, 10, 7, 6, 1, 1};
int sum= 10;
int n=8;
int i, j, index;
bool subset[sum + 1][n + 1]; // [subset_sum][subset_size]
int count[sum + 1][n + 1];
s_set lset[sum + 1][n + 1];
s_set element;
// if sum is 0, then answer is true - edge case when user provides sum vaue of 0 so no subset can exists
i = 0;
for (i; i <= n; i++)
{
subset[0][i] = true;
count[0][i] = 0;
}
// if sum is not 0 and set is empty, then answer is false - edge case when user provides empty set so no subset to be found
i = 1;
for (i; i <= sum; i++)
{
subset[i][0] = false;
count[i][0] = -1;
}
// set indexes to 0
i=0;
for (i; i <= sum; i++)
{
lset[i][0].indx=0;
}
// fill the subset table in bottom up manner
i = 1;
for (i; i <= sum; i++) { // column index
j=1;
for (j; j <= n; j++) {
subset[i][j] = subset[i][j - 1];
count[i][j] = count[i][j - 1];
lset[i][j]=lset[i][j - 1];
if (i >= set[j - 1]) {
subset[i][j] = subset[i][j] || subset[i - set[j - 1]][j - 1];
if (subset[i][j])
if ((count[i - set[j - 1]][j - 1] + 1) > count[i][j - 1]) {
count[i][j]=count[i - set[j - 1]][j - 1] + 1;
element=lset[i - set[j - 1]][j - 1];
index=element.indx;
element.arr[index]=set[j - 1];
element.indx=index+1;
lset[i][j]=element;
}
else
{
count[i][j]=count[i][j - 1];
}
}
}
}
printf("Maximum number of elements from set: %d \n", count[sum][n]);
//printf("Maximum number of elements from set: %d \n", lset[sum][n].indx);
i=0;
printf("SET{");
for (i;i<=count[sum][n]-1;i++) {
printf(" %d ", lset[sum][n].arr[i]);
}
printf("}");
return 0;
}
The problem is that if arr size in the struct s_set is too low then it will not work and will give return code 3221225477. I've gotten it to work by randomly increasing the number (40 seems to work fine), but I don't understand why does this have any effect. The index number which is used to write into arr variable should not go so high.
Working (arr size 40):
Not working (arr size 10):

average pooling C++ error

#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <math.h>
#include <fstream>
#include <iostream>
using namespace cv;
using namespace std;
#define ATD at<double>
Mat average_pooling2x2(Mat mat, int padding_mathed)
{
int width_remain = mat.cols % 2;
int high_remain = mat.rows % 2;
Mat mat_new;
if (width_remain == 0 && high_remain == 0)
mat.copyTo(mat_new);
else
{
if (padding_mathed == 1)//valid
{
Rect roi = Rect(0, 0, mat.cols - width_remain, mat.rows - high_remain);
mat(roi).copyTo(mat_new);
}
else //same
{
mat.copyTo(mat_new);
if (high_remain != 0)
{
Mat row_add = cv::Mat::zeros(high_remain, mat_new.cols,mat_new.type());
mat_new.push_back(row_add);
}
if (width_remain != 0)
{
Mat col_add = cv::Mat::zeros(width_remain, mat_new.rows, mat_new.type());
mat_new = mat_new.t();
mat_new.push_back(col_add);
mat_new = mat_new.t();
}
}
}
Mat res(mat_new.cols / 2, mat_new.rows / 2, mat_new.type(), Scalar::all(0));
if (mat_new.channels() ==3)
{
for (int i = 0; i < res.rows; i++)//this is where error happened
{
uchar *data_res = res.ptr<uchar>(i);
uchar * data = mat_new.ptr<uchar>(2*i);
uchar * data1 = mat_new.ptr<uchar>(2*i+1);
for (int j = 0; j < res.cols*res.channels(); j = j + 3)
{
data_res[j] = (data[j*2] + data[j*2+3] + data1[j*2] + data1[j*2+3]) / 4;
data_res[j + 1] = (data[j*2+1] + data[j*2+4] + data1[j*2+1] + data1[j*2+4]) / 4;
data_res[j + 2] = (data[j*2+2] + data[j*2+5] + data1[j*2+2] + data1[j*2+5]) / 4;
}
}
}
else
{
for (int i = 0; i<res.rows; i++)
{
for (int j = 0; j<res.cols; j++)
{
Mat temp;
Rect roi = Rect(j * 2, i * 2, 2, 2);
mat_new(roi).copyTo(temp);
double val;
val = sum(temp)[0] / (2 * 2);
res.ATD(i, j) = val;
}
}
}
return res;
}
int main(int argc, char** argv)
{
Mat image = imread("C://Users//Administrator//Desktop//11.jpg");
imshow("???", image);
Mat pooling_image;
average_pooling2x2(image, 2).copyTo(pooling_image);
imshow("???", pooling_image);
waitKey();
return 0;
}
OpenCV Error: Assertion failed (y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0])) in cv::Mat::ptr, file d:\opencv\build\include\opencv2\core\mat.inl.hpp, line 827
reccently I try to implement the average pooling using C++, this is the error when I run the code, it seems that maybe the ptr pointer is out of range. but I just can not figure out where is the problem. Really need some help
If you opened the file that the error message references to, you would see that the ptr() method is defined as follows:
template<typename _Tp> inline _Tp* Mat::ptr(int y)
{
CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) );
return (_Tp*)(data + step.p[0]*y);
}
Everything inside CV_DbgAssert() must evaluate to true - otherwise the program is going to crash at runtime. From that condition, it is clear that you are referring to the row in your program that is outside of Mat boundaries (the variable y above).
In your case, I can see several line where the program is going to crash.
In these lines, the crash happens when i gets equal or greater than res.rows/2 (the first one will crash if res.rows is an odd number):
uchar * data = mat_new.ptr<uchar>(2*i);
uchar * data1 = mat_new.ptr<uchar>(2*i+1);
This loop will also crash, because data_res has only res.cols columns, and you allow j to reach res.cols*res.channels()-1:
for (int j = 0; j < res.cols*res.channels(); j = j + 3)
{
data_res[j] = (data[j*2] + data[j*2+3] + data1[j*2] + data1[j*2+3]) / 4;
data_res[j + 1] = (data[j*2+1] + data[j*2+4] + data1[j*2+1] + data1[j*2+4]) / 4;
data_res[j + 2] = (data[j*2+2] + data[j*2+5] + data1[j*2+2] + data1[j*2+5]) / 4;
}
Also, I believe that here:
Mat res(mat_new.cols / 2, mat_new.rows / 2, mat_new.type(), Scalar::all(0));
you may have accidentaly swapped arguments - res has mat_new.cols/2 rows, whereas I think you wanted it to be mat_new.rows/2.

Heap Corruption detected: after Normal block(#176)

So I got this introduction to Programming assignment, I have to write a program that find the nth member of the following sequence 1, 121, 1213121, 121312141213121.. and so on. Basically, the first member is 1, and every next one is made of [the previous member] [n] [the previous member]. N < 10. So I got this problem that I do not understand, tried searching for it in the internet but didn't get anything that can help me.
#include "stdafx.h"
#include <iostream>
using namespace std;
int size(int n, int realsize);
int main()
{
int n;
cin >> n;
if (n == 1) {
cout << "1";
return 0;
}
int helper = 0;
char c = '2';
char* look;
char* say;
say = new char[size(n, 1) + 1]();
look = new char[size(n - 1, 1) + 1]();
look[0] = '1';
while (helper < n) {
for (int i = 0; i < size(helper + 1, 1); i++) {
say[i] = look[i];
}
say[size(helper + 1, 1)] = c;
for (int i = size(helper + 1, 1) + 1; i < size(helper + 1, 1) * 2 + 1; i++) {
say[i] = look[i - (size(helper + 1, 1) + 1)];
}
for (int i = 0; i < size(helper + 1, 1) * 2 + 1; i++) {
look[i] = say[i];
}
helper += 1;
}
cout << say;
delete[] say;
delete[] look;
return 0;
}
int size(int n, int realsize)
{
if (n == 1)
return realsize;
else
return size(n - 1, realsize * 2 + 1);
}
You are overwriting the capacity of your look variable. It ends out being written with the entire contents of say, so it needs to have that same size as well.
While I don't condone the below code as good code, it has minimal adjustments from your own implementation and should give a more solid base to continue towards a working outcome. I tested it with the first couple of numbers, but that's no guarantee it is perfect.
#include <iostream>
using namespace std;
int size(int n, int realsize);
int main()
{
int n;
cin >> n;
if (n == 1)
{
cout << "1";
return 0;
}
int helper = 0;
char c = '2';
char * look;
char * say;
say = new char[size(n, 1) + 1]; // Ditch the () call, which is confusing.
look = new char[size(n, 1) + 1]; // Make the same size as "say"
look[0] = '1';
while (helper < n - 1) // You're overrunning this loop I think, so I did it to n - 1.
{
for (int i = 0; i < size(helper + 1, 1); i++)
{
say[i] = look[i];
}
say[size(helper + 1, 1)] = c + helper; // You were adding '2' every time, so this will add 2, 3, 4, etc incrementally.
for (int i = size(helper + 1, 1) + 1; i < size(helper + 1, 1) * 2 + 1; i++)
{
say[i] = look[i - (size(helper + 1, 1) + 1)];
}
for (int i = 0; i < size(helper + 1, 1) * 2 + 1; i++)
{
look[i] = say[i];
}
helper += 1;
}
say[size(n, 1)] = '\0'; // Null-terminate "say" before printing it out.
cout << say;
delete[] say;
delete[] look;
return 0;
}
int size(int n, int realsize)
{
if (n == 1)
return realsize;
else
return size(n - 1, realsize * 2 + 1);
}

Undeclared identifier error where none seems apparent

I am trying to implement a simple version of Conway's Game of Life which consists of a header file and three .cpp files (two for class functions, one for main). Here I have included my header files and two class function declaration files ( the compiler is having no problem with my Main.cpp file).
Game_Of_Life.h
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
class cell{
public:
cell();
int Current_State(); // Returns state (1 or 0)
void Count_Neighbours(cell* A); // Counts the number of living cells in proximity w/o wraparound
void Set_Future(); // Determines the future value of state from # of neighbbours
void Update(); // Sets state to value of future state
void Set_Pos(unsigned int x, unsigned int y); // Sets position of cell in the array for use in counting neighbours
private:
int state;
int neighbours;
int future_state;
int pos_x;
int pos_y;
};
class cell_array{
public:
cell_array();
void Print_Array(); // Prints out the array
void Update_Array(); // Updates the entire array
void Set_Future_Array(); // Sets the value of the future array
private:
cell** A;
};
Cell_Class_Functions.cpp
#include "Game_Of_Life.h"
cell::cell(){
state = rand() % 2;
return;
}
void cell::Set_Future (){
if (state == 1){
if (neighbours < 2) future_state = 0;
else if (neighbours == 2 || neighbours == 3) future_state = 1;
else if (neighbours > 3) future_state = 0;
}
else{
if (neighbours == 3) future_state = 1;
}
return;
}
void cell::Update (){
state = future_state;
return;
}
int cell::Current_State (){
return state;
}
void cell::Set_Pos (unsigned int x, unsigned int y){
pos_x = x;
pos_y = y;
return;
}
void Count_Neighbours (cell* A){
neighbours = 0;
if (pos_x > 0) neighbours += A[pos_y * 10 + pos_x - 1].Current_State();
if (pos_x < 9) neighbours += A[pos_y * 10 + pos_x + 1].Current_State();
if (pos_y > 0) neighbours += A[(pos_y - 1) * 10 + pos_x].Current_State();
if (pos_y < 9) neighbours += A[(pos_y + 1) * 10 + pos_x].Current_State();
if (pos_x > 0 && pos_y > 0) neighbours += A[(pos_y - 1) * 10 + pos_x - 1].Current_State();
if (pos_x > 0 && pos_y < 9) neighbours += A[(pos_y + 1) * 10 + pos_x - 1].Current_State();
if (pos_x < 9 && pos_y > 0) neighbours += A[(pos_y - 1) * 10 + pos_x + 1].Current_State();
if (pos_x < 9 && pos_y < 9) neighbours += A[(pos_y + 1) * 10 + pos_x + 1].Current_State();
return;
}
Cell_Array_Class_Functions.cpp
#include "Game_Of_Life.h"
cell_array::cell_array(){
A = (cell**) malloc (sizeof(cell*)*100);
for (unsigned int r = 0; r < 10; r++){
for (unsigned int c = 0; c < 10; c++){
*A[r * 10 + c].Set_Pos(r,c);
}
}
return;
}
void cell_array::Update_Array(){
for (unsigned int r = 0; r < 10; r++){
for (unsigned int c = 0; c < 10; c++){
*A[r * 10 + c].Update();
}
}
}
void cell_array::Set_Future_Array(){
for (unsigned int r = 0; r < 10; r++){
for (unsigned int c = 0; c < 10; c++){
*A[r * 10 + c].Count_Neighbours(A);
*A[r * 10 + c].Set_Future();
}
}
return;
}
void cell_array::Print_Array(){
cout << "\n";
for (unsigned int r = 0; r < 10; r++){
for (unsigned int c = 0; c < 10; c++)cout << *A[r * 10 + c].Current_State() << " ";
cout << "\n";
}
return;
}
As far as I understand, since I included the header file with the class declarations, then I should be able to access the private members of the class through the previously declared functions in the class.
Essentially the Error Report Looks Like
Error C2065 'item' : undeclared identifier
This error appears for every private member called from the cell class.
What am I doing wrong?
Also, in your Cell_Array_Class_Functions.cpp you need to adjust your functions.
The . operator is used on objects and references.You have to deference it first to obtain a reference. That is:
(*A[r * 10 + c]).Set_Pos(r,c);
Alternatively, you can use (this is the preferred and easier to read way):
A[r * 10 + c]->Set_Pos(r,c);
The two are equivalent.
I don't see the word item anywhere in your code. However, you need to fix:
void Count_Neighbours (cell* A){ ... }
It should be:
void cell::Count_Neighbours (cell* A){ ... }