passing values in C++ - treat 1: exc bad access [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have problems with following code:
void mc_duurtijd(int multiproject)
{
double random_getal[MULTIPROJECT][PROJECTEN][ACTIVITEITEN][RUNS];
double stochastische_duurtijd_berekenen[MULTIPROJECT][SCENARIO][PROJECTEN][ACTIVITEITEN][RUNS];
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis(0, 1);
for (int p=0;p<PROJECTEN;p++)
{
for (int i=1;i<n_p[multiproject][p]-1;i++)
{
for (int r = 0; r < RUNS; r++)
{
random_getal[multiproject][p][i][r]=dis(gen);
}
}
}
for (int s=0;s<SCENARIO;s++)
{
for (int p=0;p<PROJECTEN;p++)
{
for (int i=1;i<n_p[multiproject][p]-1;i++)
{
for (int r=0;r<RUNS;r++)
{
stochastische_duurtijd_berekenen[multiproject][s][p][i][r]=bepaal_stochatische_duurtijd(random_getal[multiproject][p][i][r],multiproject,s, p, i, r);
}
}
}
}
for (int s=0;s<SCENARIO;s++)
{
for (int p=0;p<PROJECTEN;p++)
{
for (int i=1;i<n_p[multiproject][p]-1;i++)
{ stochastische_duurtijd[multiproject][s][p][i]=0.0;
for (int r=0;r<RUNS;r++)
{
stochastische_duurtijd[multiproject][s][p][i]+=stochastische_duurtijd_berekenen[multiproject][s][p][i][r];
}
stochastische_duurtijd[multiproject][s][p][i]=stochastische_duurtijd[multiproject][s][p][i]/RUNS;
}
}
}
for (int s=0;s<SCENARIO;s++)
{
for (int p=0;p<PROJECTEN;p++)
{
for (int i=1;i<n_p[multiproject][p]-1;i++)
{
stochastische_duurtijd[multiproject][s][p][i]=floor(stochastische_duurtijd[multiproject][s][p][i]/scale+0.5)*scale;
}
}
}
void berekeningen_initieel(int multiproject)
{
mc_duurtijd(multiproject);
bereken_CP_per_project_stochastisch(multiproject);
bereken_CP_max_stochastisch(multiproject);
for (int s=0;s<SCENARIO;s++)
{
bereken_backward_stochastisch(multiproject, s);
}
for (int s=0;s<SCENARIO;s++)
{
bereken_slack_stochastisch(multiproject);
}
toekennen_activiteitID(multiproject);
}
int main()
{
mp =0;
scale=0.000000000001;
srand(time(NULL)); // the random seed is initialized to a value representing the current time (calling time) to generate a different value every time the program is run.
inlezen_data();
print_output();
for (int multi =0; multi<MULTIPROJECT;multi++)
{
berekeningen_initieel(multi);
maak_planning(multi);
bereken_doelfunctie(multi);
print_evaluatie(multi);
}
return 0;
}
The problem starts when I try to run berekeningen_initieel(multi); So for the first iteration multi =0. I am passing this value into the function berekeningen_initieel(int multiproject). Here multiproject = 0 which is normal. But then I want to call the function mc_duurtijd (int multiproject). So I do this by doing mc_duurtijd(multiproject). Here the value of multiproject is equal to 0. but when I debug my code the function mc_duurtijd(int multiproject), here multiproject is NOT equal to zero but to 18455399351 (this all the time changes when I try to run my program). I really don't understand why the value 0 is not passing to the mc_duurtijd(int multiproject) function. Can someone help me?

Almost all C execution environments use a stack to store local variables and return addresses from nested function calls. The size of the stack is usually configurable; typically it is capped at 1 MiB or so.
Given MULTIPROJECTEN = 420; PROJECTEN=3; ACTIVITEITEN=32; RUNS=100 random_getal in mc_duurtijd is approximately 32 MiB in size. Attempting to execute the program results in a stack overflow.
Use dynamic memory allocation (i.e. malloc) for large buffers.

As pointed by #Nick, I also confirmed that this is most probably because of your array is too big for a function. But there is a workaround for this. You can move the array declaraation to outside function like this:
#define MULTIPROJECTEN 420
#define SCENARIO 4
#define PROJECTEN 3
#define ACTIVITEITEN 32
#define RUNS 100
double random_getal[MULTIPROJECT][PROJECTEN][ACTIVITEITEN][RUNS];
double stochastische_duurtijd_berekenen[MULTIPROJECT][SCENARIO][PROJECTEN][ACTIVITEITEN][RUNS];
void mc_duurtijd(int multiproject) { ... }
void berekeningen_initieel(int multiproject) { ... }
int main() { ... }

Related

Dynamic allocation of float matrix causes Access violation writing location error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 months ago.
Improve this question
I've received the source code of an MFC application, but when I start it I get an access violation writing location error.
Here below the VS project General configuration:
Project configuration
I cannot share the full source code, but the culprit lines are the followings:
#include <iostream>
using namespace std;
int main()
{
float** ppfPoints[2];
int maxIteration = 300000;
for (int i = 0; i < 2; i++)
{
ppfPoints[i] = (float**)new float[maxIteration];
for (int j = 0; j < maxIteration; j++)
{
ppfPoints[i][j] = new float[3];
cout<<j<<" ";
}
}
return 0;
}
If I run it on onlinegdb (uncommenting the print) the code stops while printing the value 151479.
The fun fact (at least for me) is that if I change the maxIteration value to 50000 the program stops at the value 26598.
In any case onlinegdb says "...Program finished with exit code 0", while on my MSVC compiled application I have the previously mentioned error.
Could anyone help me pointing out where the error is?
Thank you in advance!
Here are the problems:
Casting of a float* to a float**
Didn't declare the matrix correctly (should be new float*[matrix_height])
#include <iostream>
using namespace std;
int main()
{
float** ppfPoints = new float*[2]; // array (pointers) of array (pointers) of floats = (float**)
int maxIteration = 300000;
for (int i = 0; i < 2; i++)
{
ppfPoints[i] = new float[maxIteration]; // returns a pointer to an array of float (float*)
for (int j = 0; j < maxIteration; j++)
{
ppfPoints[i][j] = 0.f; // a float (float)
cout<<j<<" ";
}
}
return 0;
}
C++ style for your code (I had to guess some variable names, I hope you can do better, since you know what your code should be doing).
#include <iostream>
#include <vector>
int main()
{
// datastructure sizes use std::size_t
static constexpr std::size_t maxIteration{ 30ul }; // smaller number for demo
static constexpr std::size_t dimensions{ 2ul };
// no need to use `hungarian notation` name things after what they are (not how they are implemented).
// this line alone allocates all data and sets it to 0.0f
std::vector<std::vector<float>> point_data(dimensions, std::vector<float>(maxIteration, 0.0f));
// and use range based for loops if you can
// example of setting all values to 1.0f
for (auto& dimension : point_data) // dimensions
{
for (auto& value : dimension) // maxIteration
{
value = 1.0f; //
std::cout << value << " ";
}
std::cout << "\n";
}
return 0;
}

Is there a way to produce random numbers simultaneously in c++? If not, is there a work around? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
class Class{
int produceRandom(){
int ranNum = rand() % 5;
//other unrelated code
return ranNum;
}
std::vector<Class> classes;
int main(){
srand(time(NULL));
//codey code, unrelated
if (classes.empty() == false){
for (int i = 0; i < classes.size(); i++){
//Code produces a number of classes if certain conditions are met
int useRanNum = classes[i].produceRandom();
}
}
}
The numbers are random enough for each iteration through the code, but each classes produces the same number for each iteration.
I've hit a complete block here and it's driving me insane. Is their a work around? Am I doing something wrong? I've tried using a Mersenne Twister, but to the same result. Any help is greatly appreciated.
You can indeed if you use the random library: https://en.cppreference.com/w/cpp/header/random
#include <random>
#include <iostream>
class Class{
private:
std::random_device rd;
std::mt19937 mt;
std::uniform_int_distribution<int> dist;
public:
Class() : rd(), mt(rd()), dist(0, 100) {}
int produceRandom() {
return dist(mt);
}
};
int main()
{
Class r;
for(int i = 0; i < 10; ++i)
{
std::cout << r.produceRandom() << '\n';
}
return 0;
}
Two possible bugs:
This line:
for (int i; i < classes.size(); i++){
i is uninitialized. Hence undefined behavior and/or consistently weird results. Should be:
for (int i = 0; i < classes.size(); i++){
Also, no point in checking classes.empty() == false, the corrected loop initialization will do that for you.
But my psychic powers suggest there's another call to srand(N) lurking in the code or Where N is some constant value. Quite possibly in the section of code you aren't showing yet, and/or a library you are calling into.
A possible fix is to move the srand(time(NULL)) call after "codey code, unrelated" and before the loop.
That is:
int main(){
//codey code, unrelated
srand(time(NULL)); // move this line to be directly before the loop.
if (classes.empty() == false){
for (int i = 0; i < classes.size(); i++){
//Code produces a number of classes if certain conditions are met
int useRanNum = classes[i].produceRandom();
}
}
}

why is bubble sort not working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Given some numbers and the amount of numbers, I have to sort them in ascending order, then output how many passes and swaps were done. Why is it not working? Also, I wanted to use a vector for this problem; am i passing the vector into the function and calling it properly?
//bubble Sort
#include<iostream>
#include<vector>
using std::cin;
using std::cout;
bool isSorted(std::vector<int> & myData);
int main()
{
std::vector<int> myData;
int length = 0;
int pass = 0;
int swap = 0;
cin >> length;
int x = 0;
for(x; x < length; x++)
{
int input = 0;
cin >> input;
myData.push_back(input);
}
x = 1;
while(!isSorted(myData))
{
int trash = 0;
for(x; x < length; x++)
{
if(myData[x] < myData[x-1])
{
trash = myData[x];
myData[x] = myData[x-1];
myData[x-1] = trash;
swap++;
}
}
pass++;
}
cout << pass << " " << swap;
return 0;
}
bool isSorted(std::vector<int> & myData)
{
for(int i = 1; i < myData.size(); i++)
{
if(myData[i] < myData[i-1])
{
return false;
}
}
return true;
}
You do not reset x between iterations of bubble sort. What happens is that before the first iteration of your outer loop x is equal to one. You then run the inner while loop until x becomes length, and go to the next iteration of the outer loop. By the next iteration x is never reset, so it still equals to length, so nothing happens on the second iteration, the inner loop immediately breaks without doing any work. You go to the third iteration of the outer loop, and nothing happens again. In particular, your array never becomes sorted, so the outer while loop never breaks, and the program never finishes (and never prints anything).
To fix it, just move x = 1 inside the loop, like this:
...
while(!isSorted(myData))
{
x = 1;
int trash = 0;
...

Recursion call failure

I'm creating a suduko generator and I either get a stack overflow when calling a function using recursion or it doesn't call the function when it is being called with the class, I can't explain very well what is happening but this is the code:
sudoku::sudoku()
{
srand((unsigned int)time(NULL));
generate(); // call the generate function
display(1);
}
sudoku::~sudoku()
{}
bool sudoku::validate(){ //makes sure not more than one of the same number in row/column
for (int x = 0; x < size; x++){
for (int y = 0; y < size; y++){
if (number == Array[x][y])
return true;
}
}
return false;
}
void sudoku::generate(){ // generates sudoku numbers which is 9x9
for (int x = 0; x < size; x++){
for (int y = 0; y < size; y++){
number = 1;
if (validate() == true){
generate(); //get a stack overflow with this call
//if I change "generate" to "sudoku generate" the
//stack overflow doesn't happen but then the function
} //is not called, the if statement just skips to the else
else{
Array[x][y] = number;
}
}
}
}
is there a way to call "sudoku generate()" without the if statement skipping the condition even when it is true? Or is there another way of doing this?
First of all the if statement is redundant
if(validate()==true)
validate returns a boolean right? why equate this to another boolean you can write this as:
if(validate())
The stack overflow might be caused of too many calls of the generate() and validate() function, remember each call of the recursion pushes another instance of this functions to the stack. To solve this you might want to take a look at the principles of communicating vases : https://www.youtube.com/watch?v=q1G6S0DbnJY
or you can audit this course on edX which gives a quick look at invariant programming and principles of communicating vases : https://courses.edx.org/courses/LouvainX/Louv1.01x/1T2014/info

C++ program cant find mistake [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
this program creates random number array where elements wit arguments 1,3,5,7...,19 are negative and this program should find biggest negative element but when l test program it writes some random number (6784345 instead of array element) can you help me find mistake ?
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void najneg(int *pa,int *nn)
{
nn=0;
for(int i=0;i<20;i++)
{
if((pa+i)<nn) nn=(pa+i);
}
}
int main()
{
int a[20],nn,i;
srand(time(0));
for(i=0;i<20;i++)
{
if(i%2==0) a[i]=rand()%(61);
else
a[i]=(rand()%(61))*(-1);
}
printf("Formirani niz je:\n");
for(int i=0;i<20;i++)
{
printf("\ "); printf("%d",a[i]);
}
najneg(a,&nn);
printf("\n\nNajveci negativni clan niza je:%d\n",nn);
return 0;
}
In this code, …
void najneg(int *pa,int *nn)
{
nn=0;
for(int i=0;i<20;i++)
{
if((pa+i)<nn) nn=(pa+i);
}
}
you forgot to dereference the pointers,
void najneg(int *pa,int *nn)
{
*nn=0;
for(int i=0;i<20;i++)
{
if(*(pa+i)<*nn) *nn=*(pa+i);
}
}
The most important fix for this function is to change its name to something readable and self-descriptive, with no arbitrary shortenings. When choosing names, think about making the calling code readable and clear. So E.g., najneg → most_negative_value_in.
Secondly, instead of logical out-argument, use the function return value.
Third, if the function doesn't need to change data, use const to let it offer a guarantee that it won't change the data.
Fourth, avoid magic numbers like 20: pass the array size as argument.
This, plus some purely cosmetic changes, yields:
int most_negative_number_in(int const* const a, int const size)
{
int n=0;
for(int i=0; i<size; ++i)
{
if(a[i]<n) { n = a[i] };
}
return n;
}
This function should be
void najneg(int *pa,int *nn)
{
*nn=0; //As you want to modify nn.
for(int i=0;i<20;i++)
{
if(pa[i]<*nn) *nn=pa[i]; //Here, you want to compare values and swap them. Not just address.
}
}
Do not try to complicate it.
In addition to what others have pointed out:
You can simplify the content of your for loops:
for(i = 0; i < 20; i++)
{
// The array slot is assigned a random value
// whether the index is positive or negative.
a[i] = rand() % 61;
// If the index is odd, change the value
// to a negative number.
if(i % 2 == 1)
{
a[i] *= -1;
}
}
In the next loop, you should combine into one printf call:
for(int i = 0; i < 20; i++)
{
printf("\ %d", a[i]);
}
Also, what is "\ " in the format specifier, a tab or a space?