I am java programmer but still finding this c++ code not working. When I run this project (Codeblock), I get the segmentation fault. I searched internet but couldn't find exactly what causing this error.
1) main.cpp
#include "performancetest.h"
int main(int argc, char *argv[])
{
performancetest *Obj = new performancetest;
Obj->test1();
Obj->test2();
Obj->~performancetest();
return 0;
}
2) performancetest.cpp
#include "performancetest.h"
#include <iostream>
using namespace std;
performancetest::performancetest()
{
}
performancetest::~performancetest()
{
}
void performancetest::test1()
{
clock_t t1, t2;
const int g_n = 500;
float TestData[g_n][g_n][g_n];
t1 = clock();
for (int k=0; k<g_n; k++) // K
{
for (int j=0; j<g_n; j++) // J
{
for (int i=0; i<g_n; i++) // I
{
TestData[i][j][k] = 0.0f;
}
}
}
//start time t2
t2 = clock();
double val = this->diffclock(t1, t2);
cout << "Time: " << val << endl;
}
void performancetest::test2()
{
clock_t t1, t2;
const int g_n = 500;
float TestData[g_n][g_n][g_n];
//start time t1
t1 = clock();
for (int k=0; k<g_n; k++) // K
{
for (int j=0; j<g_n; j++) // J
{
for (int i=0; i<g_n; i++) // I
{
TestData[i][j][k] = 0.0f;
}
}
}
//start time t2
t2 = clock();
double val = this->diffclock(t1, t2);
cout << "Time: " << val << endl;
}
double performancetest::diffclock(clock_t clock1,clock_t clock2)
{
double diffticks=clock1-clock2;
double diffms=(diffticks)/(CLOCKS_PER_SEC/1000);
return diffms;
}
3)performancetest.h
#ifndef PERFORMANCETEST_H
#define PERFORMANCETEST_H
#include <time.h>
class performancetest
{
public:
performancetest();
void test1();
double diffclock(clock_t, clock_t);
void test2();
virtual ~performancetest();
protected:
private:
};
#endif // PERFORMANCETEST_H
And, here comes, segmentation fault as shown in below picture
Your multidimensional arrays are too big for the stack, so a stack overflow exception is thrown. You must allocate TestData on the heap.
You can do it like this:
const int g_n = 500;
typedef float MultiDimArray[g_n][g_n];
MultiDimArray* TestData = new MultiDimArray[g_n];
//...
delete[] TestData; //deallocate
Related
Doing hackerrank problem "Attending Workshops" https://www.hackerrank.com/challenges/attending-workshops/problem
I have the problem that I can't sort my vector. I tried with a lambda (in commentary) and then by overloading the operator >.
My vector never turn out to be sorted. Can you help me find what I did wrong. Here is my code:
#include<bits/stdc++.h>
using namespace std;
//*************ABOVE IS LOCKED CODE BY HACKERRANK****************;
//Define the structs Workshops and Available_Workshops.
//Implement the functions initialize and CalculateMaxWorkshops
struct Workshop
{
int startTime;
int endTime;
int duration;
Workshop(){}
Workshop(int pStartTime, int pDuration)
:startTime(pStartTime), duration(pDuration)
{
endTime = startTime + duration;
}
bool operator < (const Workshop &other) const
{
cout << "trace inside operator never showing up" << endl;
return endTime < other.endTime;
}
};
struct Available_Workshops
{
int nbWorkshop;
vector<Workshop> workshops;
Available_Workshops(int *start_times, int *durations, int n)
:nbWorkshop(n)
{
workshops.reserve(n);
for(int i = 0; i < n; ++i)
{
workshops[i] = Workshop(start_times[i], durations[i]);
}
}
};
Available_Workshops *initialize(int *start_time, int *duration, int n)
{
return new Available_Workshops(start_time, duration, n);
}
int CalculateMaxWorkshops(Available_Workshops *avai_work_ptr)
{
//The two for loops are just there to trace the content of avai_work_ptr->nbWorkshop to validate sorting...
for(int i = 0; i < avai_work_ptr->nbWorkshop; ++i)
cout << avai_work_ptr->workshops[i].startTime << " " << avai_work_ptr->workshops[i].endTime << endl;
std::sort(avai_work_ptr->workshops.begin(), avai_work_ptr->workshops.end());//, [](const Workshop &a, const Workshop &b){cout << "compar"; return a.startTime < b.startTime;});
for(int i = 0; i < avai_work_ptr->nbWorkshop; ++i)
cout << avai_work_ptr->workshops[i].startTime << " " << avai_work_ptr->workshops[i].endTime << endl;
int maxWorkshop = 0;
//Chunk of code removed because it is not related to the sort problem...
//...
return maxWorkshop;
}
//*************BELOW IS LOCKED CODE BY HACKERRANK****************;
int main(int argc, char *argv[]) {
int n; // number of workshops
cin >> n;
// create arrays of unknown size n
int* start_time = new int[n];
int* duration = new int[n];
for(int i=0; i < n; i++){
cin >> start_time[i];
}
for(int i = 0; i < n; i++){
cin >> duration[i];
}
Available_Workshops * ptr;
ptr = initialize(start_time,duration, n);
cout << CalculateMaxWorkshops(ptr) << endl;
return 0;
}
Thank you.
workshops.reserve(n);
is wrong. It just do allocation and not inclease the number of valid elements, so the end() iterator will still be the top of the array.
You should use
workshops.resize(n);
instead.
I am getting the following debug error from Eclipse IDE
Failed to execute MI command:
-data-evaluate-expression *((array500000)+30000)#10000
Error message from debugger back end:
Cannot access memory at address 0x42f250
but I am not sure how to resolve the issue. Would anyone give me any advice please? I am new to coding.
Tried different IDE. My code works on online IDE but not other IDEs.
using namespace std;
using namespace std::chrono;
void Swap(int *x,int *y) {
int temp=*x;
*x=*y;
*y=temp;
}
void Insertion(int A[],int n) {
int i,j,x;
for(i=1;i<n;i++) {
j=i-1;
x=A[i];
while(j>-1 && A[j]>x){
A[j+1]=A[j];
j--;
}
A[j+1]=x;
}
}
void Merge(int A[],int l,int mid,int h) {
int i=l,j=mid+1,k=l;
int B [500000];
while(i<=mid && j<=h) {
if(A[i]<A[j])
B[k++]=A[i++];
else
B[k++]=A[j++];
}
for(;i<=mid;i++) {
B[k++]=A[i];
}
for(;j<=h;j++) {
B[k++]=A[j];
}
for(i=l;i<=h;i++) {
A[i]=B[i];
}
}
void MergeSort(int A[],int l,int h) {
if(l<h) {
int mid=(l+h)/2;
MergeSort(A,l,mid);
MergeSort(A,mid+1,h);
Merge(A,l,mid,h);
}
}
void ArrayAscend (int A[], int n) {
for (int a = 0; a < n ; a++) {
A [a] = a + 1;
}
}
void ArrayRandom (int A[], int n) {
ArrayAscend (A,n);
srand (time(NULL));
for (int i= n-1 ; i > 0; i--) {
int j = rand () % (i+1);
Swap (&A[i], &A[j]);
}
}
void ArrayDescend (int A[], int n) {
for (int a = 0; a < n ; a++) {
A [a] = n - a;
}
}
int main() {
int arraySize500000 = 500000;
int array500000[arraySize500000] = {};
cout << "*********************Insertion Sort*********************" <<endl;
cout << "---------- Arrays with 500000 Integers ----------" <<endl;
ArrayAscend (array500000,arraySize500000);
auto t1 = system_clock::now();
Insertion(array500000,arraySize500000);
auto t2 = system_clock::now();
auto duration1 = duration_cast<microseconds>(t2-t1);
cout << "Array in ascending order took " << duration1.count()<<" microseconds"<<endl;
ArrayDescend (array500000,arraySize500000);
auto t3 = system_clock::now();
Insertion(array500000,arraySize500000);
auto t4 = system_clock::now();
auto duration2 = duration_cast<microseconds>(t4-t3);
cout << "Array in descending order took " << duration2.count()<<" microseconds"<<endl;
ArrayRandom (array500000,arraySize500000);
auto t5 = system_clock::now();
Insertion(array500000,arraySize500000);
auto t6 = system_clock::now();
auto duration3 = duration_cast<microseconds>(t6-t5);
cout << "Array in random order took " << duration3.count()<<" microseconds"<<endl;
return 0;
}
I expect the output of the duration of each insertion sorts.
int B [500000];
int arraySize500000 = 500000;
int array500000[arraySize500000] = {};
Even if this is converted to a constexpr, as pointed out by John, these will create 2MB arrays on the stack. Visual Studio for example only has 1MB of stack allocated.
You should use std::vector<int> array500000(500000) instead.
So I have my program here:
#include <iostream>
#include <string>
#include <pthread.h>
#include <unistd.h>
#include <math.h>
#include <stdlib.h>
using namespace std;
int const size = 3;
struct Arguments{
int array[];
float result1[];
float result2[];
};
//void calc(int arr[], float rarr1[], float rarr2[], int size);
void* calc(void *param);
int main(int argc, char *argv[]){
time_t t;
srand((unsigned) time(&t));
int arr[size][size] = {};
float rarr1[size][size-1] = {};
float rarr2[size][size-1] = {};
for(int x = 0; x < size; x++){
for(int y = 0; y < size; y++){
int number = rand()%10;
arr[x][y] = number;
}
}
for(int x = 0; x < size; x++){
for(int y = 0; y < size; y++){
cout << arr[x][y] << " ";
}
cout << endl;
}
cout << endl;
/////////////////////////////////////////
pthread_t child;
struct Arguments input;
for(int i = 0; i < size; i++){
input.array[i] = arr[0][i];
}
pthread_create(&child, NULL, calc, (void*)&input);
pthread_join(child, NULL);
//calc(&input);
for(int i = 0; i < size-1; i++){
rarr1[0][i] = input.result1[i];
cout << "Test: " << rarr1[0][i] << endl;
}
//////////////////////////////////
return 0;
}
//void calc(int arr[], float rarr1[], float rarr2[], int size){
void* calc(void *param){
struct Arguments *input = (struct Arguments*)param;
int arr1[] = {};
float rarr1[] = {};
float rarr2[] = {};
for(int i = 0; i < size; i++){
arr1[i] = input->array[i];
}
for(int i = 0; i < size; i++){
int a = arr1[i];
int b = arr1[i+1];
int difference = a-b;
if(difference < 0){
difference = difference * -1;
}
float euc = 1 + pow(difference, 2);
euc = sqrt(euc);
rarr1[i] = euc;
}
for(int i = 0; i <size-1; i++){
input->result1[i] = rarr1[i];
}
for(int i = 0; i <size-1; i++){
int a = arr1[i];
int b = arr1[i+1];
int difference = a-b;
if(difference < 0){
difference = difference * -1;
}
float apar = (difference/rarr1[i]);
float result = asin(apar);
result = result*(180/3.14);
rarr2[i] = result;
}
return NULL;
}
The important part that causes the trouble is between ////// lines but I left the rest of the code for the context, since it might be useful.
So I have the function calc(param); that does the important calculation in the program.
It is working just fine as long as I call it myself (by actually including the function call in the code) and the test loop right after it gives the correct results.
However, when I try to use pthread_create(); to create a new thread that will take care of executing that function, the test loop spits out nonsense and some random huge numbers different each time.
It's kinda weird because the code compiles either way, and literally the only thing that I change is these 2 lines.
What am I doing wrong and why the function spits out garbage when started by the Pthread? Is there a way to fix it?
Ok so if anyone's having a similar problem:
Declare the size of arrays no matter what. It turns out that my program didn't work properly because I initialized my result arrays as float result1[]; instead of float result1[size];
I am trying to compare performance of different lock-free queues, therefore, I want to create a unit test - which includes pushing/poping user-defined pre-built objects to and from the queue. Therefore, I want to ask you couple of questions:-
1) How to create pre-built objects in a simple manner. Does creating an array like I did would fulfill the purpose.
2) I am getting an error "terminate called after throwing an instance of 'std::system_error' what(): Invalid argument Aborted (core dumped)".
Thanx in advance.
#include <cstdlib>
#include <stdio.h>
#include <string>
#include <chrono>
#include <iostream>
#include <ctime>
#include <atomic>
#include <thread>
#include <boost/lockfree/queue.hpp>
using namespace std;
const long NUM_DATA = 10;
const int NUM_PROD_THREAD = 2;
const int NUM_CONSUM_THREAD = 2;
const long NUM_ITEM = 1000000;
class Data
{
public:
Data(){}
void dataPrint() {cout << "Hello";}
private:
long i;
double j;
};
Data *DataArray = new Data[NUM_DATA];
boost::lockfree::queue<Data*> BoostQueue(1000);
struct Producer
{
void operator()()
{
for(long i=0; i<1000000; i++)
BoostQueue.push( DataArray );
}
};
struct Consumer
{
Data *pData;
void operator()()
{
while ( BoostQueue.pop( pData ) ) ;
}
};
int main(int argc, char** argv)
{
std::thread thrd [NUM_PROD_THREAD + NUM_CONSUM_THREAD];
std::chrono::duration<double> elapsed_seconds;
auto start = std::chrono::high_resolution_clock::now();
for ( int i = 0; i < NUM_PROD_THREAD; i++ )
{
thrd[i] = std::thread{ Producer() };
}
for ( int i = 0; i < NUM_CONSUM_THREAD; i++ )
{
thrd[NUM_PROD_THREAD+i] = std::thread{Consumer()};
}
for ( int i = 0; i < NUM_CONSUM_THREAD; i++ )
{
thrd[i].join();
}
auto end = std::chrono::high_resolution_clock::now();
elapsed_seconds = end - start;
std::cout << "Enqueue and Dequeue 1 million item in:" << elapsed_seconds.count() << std::endl;
for ( int i = 0; i < NUM_PROD_THREAD; i++ )
{
thrd[i].join();
}
return 0;
}
Just illustrating how to use Data elements in the benchmark, though this does add a cout within the measured time which isn't ideal but probably isn't significant either.
class Data
{
public:
Data(long i) : i_(i) {}
void dataPrint() {cout << "Hello";}
private:
long i_;
double j;
};
Data* dataArray[1000000];
for (int i = 0; i < NUM_DATA; ++i) dataArray[i] = new Data(i);
boost::lockfree::queue<Data*> BoostQueue(1000);
struct Producer
{
void operator()()
{
for(long i=0; i<1000000; i++)
BoostQueue.push( dataArray[i] );
}
};
struct Consumer
{
Data *pData;
long result_;
void operator()()
{
result_ = 0;
while ( BoostQueue.pop( pData ) )
result_ += pData->i_;
std::cout << result_ << '\n';
}
};
int main(int argc, char** argv)
{
std::thread thrd [NUM_PROD_THREAD + NUM_CONSUM_THREAD];
std::chrono::duration<double> elapsed_seconds;
auto start = std::chrono::high_resolution_clock::now();
for ( int i = 0; i < NUM_PROD_THREAD; i++ )
thrd[i] = std::thread{ Producer() };
for ( int i = 0; i < NUM_CONSUM_THREAD; i++ )
thrd[NUM_PROD_THREAD+i] = std::thread{Consumer()};
for ( int i = 0; i < NUM_CONSUM_THREAD; i++ )
thrd[NUM_PROD_THREAD+i].join();
auto end = std::chrono::high_resolution_clock::now();
elapsed_seconds = end - start;
std::cout << "Enqueue and Dequeue 1 million item in:"
<< elapsed_seconds.count() << std::endl;
for ( int i = 0; i < NUM_PROD_THREAD; i++ )
thrd[i].join();
for (int i = 0; i < 1000000; ++i)
delete dataArray[i];
}
I'm writing a genetic algorithm for which I'm creating a "crossover" operator as a class object that is passed the two parent "chromosomes" Because the input and therefore the output chromosomes are variable lengths, my idea was two divide the input chromosomes and place in a sort of storage class variable, then resize the input chromosomes, and then finally refill the input chromosomes. I'm getting a bad_alloc error, however. If someone could spot my error I'd very much appreciate the help.
Thanks! My class code is below. Note that "plan_vector" is a 2d vector of int types.
#include <iostream>
#include <vector>
#include <eo>
class wetland_vector : public std::vector<int> {
public:
wetland_vector() : std::vector<int>(1, 0) {
}
};
std::istream& operator>>(std::istream& is, wetland_vector& q) {
for (unsigned int i = 0, n = 1; i < q.size(); ++i) {
is >> q[i];
}
return is;
}
std::ostream& operator<<(std::ostream& os, const wetland_vector& q) {
os << q[0];
for (unsigned int i = 1, n = 1; i < q.size(); ++i) {
os << " " << q[i];
}
os << " ";
return os;
}
class wetland_vector_Init : public eoInit<wetland_vector> {
public:
void operator()(wetland_vector& q) {
for (unsigned int i = 0, n = q.size(); i < n; ++i) {
q[i] = rng.random(10);
}
}
};
class plan_vector : public eoVector<double, wetland_vector> {
};
int read_plan_vector(plan_vector _plan_vector) {
for (unsigned i = 0; i < _plan_vector.size(); i++) {
//Call function that reads Quad[1]
//Call function that reads Quad[2]
//etc
return 0;
}
return 0;
};
class eoMutate : public eoMonOp<plan_vector> {
int subbasin_id_min;
int subbasin_id_max;
int wetland_id_min;
int wetland_id_max;
bool operator() (plan_vector& _plan_vector) {
//decide which Quad to mutate
int mutate_quad_ID = rng.random(_plan_vector.size());
//decide which Gene in Quad to mutate
int mutate_gene_ID = rng.random(_plan_vector[mutate_quad_ID].size());
//mutation procedure if first slot in the Quad is selected for mutation
if (mutate_quad_ID = 0) {
_plan_vector[mutate_quad_ID][mutate_gene_ID] = rng.random(subbasin_id_max);
}
//mutation procedure if second slot in the Quad is selected for mutation
if (mutate_quad_ID = 1) {
_plan_vector[mutate_quad_ID][mutate_gene_ID] = rng.random(subbasin_id_max);
}
//note: you'll need to add more for additional wetland characteristics
return true;
};
public:
void set_bounds(int, int, int, int);
};
void eoMutate::set_bounds(int a, int b, int c, int d) {
subbasin_id_min = a;
subbasin_id_max = b;
wetland_id_min = c;
wetland_id_max = d;
}
double evaluate(const plan_vector& _plan_vector) {
int count = 0;
for (int i = 0; i < _plan_vector.size(); i++) {
for (int j = 0; j < _plan_vector[i].size(); j++) {
count += _plan_vector[i][j];
}
}
return (count);
}
class eoQuadCross : public eoQuadOp<plan_vector> {
public:
std::string className() const {
return "eoQuadCross";
}
plan_vector a1;
plan_vector a2;
plan_vector b1;
plan_vector b2;
bool operator() (plan_vector& a, plan_vector& b) {
int cross_position_a = rng.random(a.size() - 1);
int cross_position_b = rng.random(b.size() - 1);
for (int i = 0; i < cross_position_a; i++) {
a1.push_back(a[i]);
}
for (int i = cross_position_a; i < a.size(); i++) {
a2.push_back(a[i]);
}
for (int i = 0; i < cross_position_b; i++) {
b1.push_back(b[i]);
}
for (int i = cross_position_b; i < b.size(); i++) {
b2.push_back(b[i]);
}
int size_a = b2.size() + a1.size();
int size_b = a2.size() + b1.size();
a.resize(size_a);
b.resize(size_b);
for (int i = 0; i < b2.size(); i++) {
a.push_back(b2[i]);
}
for (int i = 0; i < a1.size(); i++) {
a.push_back(a1[i]);
}
for (int i = 0; i < a2.size(); i++) {
b.push_back(a2[i]);
}
for (int i = 0; i < b1.size(); i++) {
b.push_back(b1[i]);
};
//Return bool
return true;
}
};
int main() {
unsigned int vec_size_min = 1;
unsigned int vec_size_max = 10;
unsigned int pop_size = 100;
//BEGIN COPY PARAMETRES
const unsigned int MAX_GEN = 100;
const unsigned int MIN_GEN = 5;
const unsigned int STEADY_GEN = 50;
const float P_CROSS = 0.8;
const float P_MUT = 0.5;
const double EPSILON = 0.01;
double SIGMA = 0.3;
const double uniformMutRate = 0.5;
const double detMutRate = 0.5;
const double normalMutRate = 0.5;
//END COPY PARAMETERS
rng.reseed(1);
//Create population
wetland_vector_Init atom_init;
eoInitVariableLength<plan_vector> vec_init(vec_size_min, vec_size_max, atom_init);
eoPop<plan_vector> pop(pop_size, vec_init);
//Create variation operators
eoMutate mutate;
mutate.set_bounds(1, 453, 1, 4);
eoQuadCross crossover;
eoDetTournamentSelect<plan_vector> select(3);
eoSGATransform<plan_vector> transform(crossover, .5, mutate, .2);
//Create fitness function
eoEvalFuncPtr<plan_vector> eval(evaluate);
//Evaluate initial population and cout
apply<plan_vector > (eval, pop);
std::cout << pop << std::endl;
//Set GA for execution and execute
eoGenContinue<plan_vector> GenCount(5);
eoSGA<plan_vector> gga(select, crossover, .5, mutate, .1, eval, GenCount);
gga(pop);
//cout final population and end
std::cout << pop << std::endl;
std::cout << "The End" << std::endl;
}
a1.~vector();
a2.~vector();
b1.~vector();
b2.~vector();
You shall not destruct the vectors manually, otherwise the next time you try to access them (upon next call to the operator ()) you get undefined behavior.
Why do you call vector destructor manually?? You should let C++ call that for you. If you want to clear the vector use clear member function