C++ EXC_BAD_ACCESS what does it mean? - c++

I'm trying to write my first neural network in C++ and I'm having trouble with it.
Basically I get
segmentation fault 11
So I tried to debug and it turned out that after the line 41 the program stops for a reason called
EXC_BAD_ACCESS,
what does it mean? how can I turn around it? I've seen from other posts that segmentation fault means running out of stack, which would be an issue because that's maybe the 30% of the code that I planned to write
anyway here is my code, I put in the comment what was line 41 (see comment)
#include <vector>
#include <iostream>
#include <cstdlib>
#include <cassert>
#include <cmath>
#include <fstream>
#include <sstream>
using namespace std;
struct Connection
{
double w;
double dw;
};
class Neuron;
typedef vector<Neuron> Layer;
//*************************** class Neuron ***************
class Neuron
{
public:
Neuron(unsigned numOutput, unsigned MyIndex);
void setOtpuVal(double Val){m_outputVal = Val; }
double getOutputval(void) const {return m_outputVal; }
void feedForward (const Layer &prevLayer);
private:
static double randomWeight(void) {return (rand()/(RAND_MAX));}
unsigned m_MyIndex;
double m_outputVal;
vector<Connection> m_outputWeights;
};
void Neuron::feedForward (const Layer &prevLayer){
double sum = 0.0; //<===================================that's line 40
for (unsigned i = 0; i < prevLayer.size(); ++i)
{
sum += prevLayer[i].getOutputval() * prevLayer[i].m_outputWeights[m_MyIndex].w;
}
}
Neuron::Neuron(unsigned numOutput, unsigned MyIndex){
for (unsigned c = 0; c < numOutput; ++c)
{
m_outputWeights.push_back(Connection());
m_outputWeights.back().w = randomWeight();
}
m_MyIndex = MyIndex;
}
//*************************** class Net *********************
class Net{
public:
Net (const vector<unsigned> &Topology);
void feedForward(const vector<double> &Input );
void backProp (const vector<double> &Target){};
void getResults(vector<double> &Output) const{}; //const non modifica l'oggetto
private:
std::vector<Layer> m_layer; // m_layer []
};
void Net::feedForward (const vector<double> &Input ) {
//assert(Input.size() == m_layer[0].size()-1);
// assert(inputVals.size() == m_layers[0].size() - 1);
//feeding
for (unsigned i = 0; i < Input.size()-1; ++i) {
m_layer [0] [i].setOtpuVal(Input[i]);
}
//foorward propagatin
for (unsigned i = 0; i < m_layer.size(); ++i)
{
Layer &prevLayer = m_layer[i-1];
for (unsigned j = 0; j < m_layer[i].size(); ++j)
{
m_layer[i][j].feedForward(prevLayer);
}
}
}
Net::Net (const vector<unsigned> &Topology){
unsigned numLayer = Topology.size();
for (unsigned i = 0; i < numLayer; ++i)
{
m_layer.push_back(Layer());
unsigned numOutput = i == Topology.size() - 1 ? 0 : Topology[i +1]; //inportante!!!!
for (unsigned j = 0; j <= Topology[i]; ++j)
{
m_layer.back().push_back(Neuron(numOutput,j));
cout<<"made a Neuron"<<endl;
}
}
}
int main(int argc, char const *argv[])
{
ifstream reader("Istruzioni.txt",ios::in);
std::vector<double> Input;
std::vector<double> Target;
std::vector<double> Output;
std::vector<unsigned> Topology;
Topology.push_back(3);
Topology.push_back(2);
Topology.push_back(1);
Net MyNet(Topology);
char letter;
for (int i = 0; i < 4; ++i)
{
reader.get(letter);
if (i == 3)
{
Target.push_back( (float)letter - 48);
}
else
Input.push_back((float)letter - 48);
}
reader.close();
MyNet.feedForward (Input);
MyNet.backProp(Target);
MyNet.getResults(Output);
return 0;
}

The error message and behavior is typical for an invalid memory access. It is one of the possible symptom of UB. So what can be said hereafter is only a probable explanation, but nothing for sure.
Looking at the code, and assuming it was called with a valid prevLayer argument:
for (unsigned i = 0; i < prevLayer.size(); ++i)
{
sum += prevLayer[i].getOutputval() * prevLayer[i].m_outputWeights[m_MyIndex].w;
}
it is with high probability an access out of bounds. Since i is in principle within bounds, so the trouble come m_MyIndex.
What to do ?
Check if that member is properly initialized.
Check if its value is positive and that it's smaller than prevLayer[i].m_outputWeights.size()
If this doesn't help solve the issue, it means that some other place in the code messed up (e.g. prevLayer already refers to an object that doesn't exist, or some memory corruption happened before and didn't show any consequence until this moment).

Related

Undefined reference to 'image::numbers'

I get this error when I compile this code in my compiler.
I tested this code in VSCode and I didn't get any error but in 'codeblocks' IDE, I get this error:
ERROR: undefined reference to 'Image::numbers'
This is my code:
note: I don't write those pieces of my code which they are not so important to solve my problem, like 'getWidth() function' etc.
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
class Image
{
private:
static vector < vector < vector<bool> > > numbers;
static void setImageMatrix(ifstream& image, vector< vector< vector<bool> > > &matrix, int index)
{
int width = getWidth(image);
int height = getHeight(image);
int zeros = getNumberOfZeros(width);
int lineCharsNumber = width * 3 + zeros;
char pixelsLine[lineCharsNumber];
int end = width*3;
vector <bool> tempVector;
for(int i = 0; i < height; i++)
{
image.read(pixelsLine, lineCharsNumber);
tempVector.clear();
for (int j = 0; j < end; j+=3)
{
int average = charToInt(pixelsLine[j]) * 0.11 + charToInt(pixelsLine[j+1]) * 0.59
+ charToInt(pixelsLine[j+2]) * 0.3;
if(average < 70)
tempVector.push_back(true);
else
tempVector.push_back(false);
}
matrix[index].push_back(tempVector);
}
}
void static setNumbersMatrix()
{
ifstream zeroPic("F:\\Projects\\C++\\-[Project1]Image_Processing\\Images\\0.bmp", ios::in | ios::binary);
setImageMatrix(zeroPic, numbers, 0);
}
and at last: sorry about my English, I appreciate that if you help me, thanks!

Why do I need different sorting formats in C++ for sorting arrays and priority queues on this USACO code?

I'm pretty new to C++, and was trying a USACO problem from this past year. This is my code below, which works, but took hours to fiddle around with the formatting. It turns out that I needed
bool sorting(total a, total b) {return a.t < b.t;}
to be able to sort an array of objects (which failed for my priority queue), whereas I needed
struct uppersort {
bool operator()(bounded a, bounded b) {
return a.u > b.u;
}
};
to be able to sort a priority queue (which failed for my array). I'm just wondering why this was true, and if there's a simpler way to do either part. Actually, I'm also just looking for ways to simplify my code in general. Thanks!
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
struct bounded {
int cow;
long l;
long u;
};
struct total {
long t;
long whichcow;
bool begorend;
};
struct uppersort {
bool operator()(bounded a, bounded b) {
return a.u > b.u;
}
};
bool sorting(total a, total b) {return a.t < b.t;}
int main() {
ofstream fout ("lifeguards.out");
ifstream fin ("lifeguards.in");
long n;
fin >> n;
vector<bounded> cows(n);
for(int i=0; i<n; i++) {
fin >> cows[i].l >> cows[i].u;
cows[i].cow = i;
}
vector<total> endpoints(2*n);
for(int i=0; i<n; i++) {
endpoints[i].t = cows[i].l;
endpoints[i].whichcow = i;
endpoints[i].begorend = 0;
endpoints[n+i].t=cows[i].u;
endpoints[n+i].whichcow = i;
endpoints[n+i].begorend = 1;
}
sort(endpoints.begin(), endpoints.end(), sorting);
int containnumber = 0;
long totaltime = 0;
vector<long> eachtime(n);
long prevtime = 0;
long curtime = 0;
priority_queue<bounded, vector<bounded>, uppersort> contains;
for(int i=0; i<2*n; i++) {
prevtime = curtime;
curtime = endpoints[i].t;
if(containnumber==1) {
eachtime[contains.top().cow] += curtime - prevtime;
}
if(containnumber >0) {
totaltime += curtime - prevtime;
}
if(endpoints[i].begorend==0) {
contains.push(cows[endpoints[i].whichcow]);
containnumber++;
} else {
contains.pop();
containnumber--;
}
}
long min = -1;
for(int i=0; i<n; i++) {
if(min==-1 || eachtime[i]<min) {
min = eachtime[i];
}
}
fout << totaltime-min << endl;
}
Both sort and priority_queue are expecting the provided type to be sort-able (have operator<).
Since neither your bounded nor your total do, you have to provide your own function in both cases. The difference in format you asked about is just an artifact of the interface.
In both cases the simpler or more elegant solution is to define the comparison operators on your types.
struct bounded {
int cow;
long l;
long u;
bool operator<(bound rhs)const{
return u<rhs.u;
}
};
struct total {
long t;
long whichcow;
bool begorend;
bool operator<(total rhs)const{
return t<rhs.t;
}
};
You should fill in the rest of the comparison operators for good form (or just compare_three_way, operator<=>, if you are using c++20 or newer).

2D array in a class using c++

I wrote a code to present a class Third takes instances of other two classes One , and Two respectively , everything was working fine until i added a matrix Mat , and the method get_Mat in the third class , in the code it has the name Third, this code doesn't produce any error message , but when execute it does until the line before return 0 in main , then it terminate as something wrong was encountered by the compiler and need to be closed , i wish that you can help me find the problem.
Thanks.
#include<iostream>
#include<vector>
#include <stdlib.h>
using namespace std;
class One // this the first class
{
private:
unsigned int id;
public:
unsigned int get_id(){return id;};
void set_id(unsigned int value) {id = value;};
One(unsigned int init_val = 0): id(init_val) {}; // constructor
~One() {}; // destructor
};
////////////////////////////////////////////////////////////////////
class Two // the second class
{
private:
One first_one;
One second_one;
unsigned int rank;
public:
unsigned int get_rank() {return rank;};
void set_rank(unsigned int value) {rank = value;};
unsigned int get_One_1(){return first_one.get_id();};
unsigned int get_One_2(){return second_one.get_id();};
Two(const One& One_1 = 0, const One& One_2 =0 , unsigned int init_rank = 0)
: first_one(One_1), second_one(One_2), rank(init_rank)
{
}
~Two() {} ; // destructor
};
/////////////////////////////////////////////////////////////
class Three // the third class
{
private:
std::vector<One> ones;
std::vector<Two> twos;
vector<vector<unsigned int> > Mat;
public:
Three(vector<One>& one_vector, vector<Two>& two_vector)
: ones(one_vector), twos(two_vector)
{
for(unsigned int i = 0; i < ones.size(); ++i)
for(unsigned int j = 0; j < ones.size(); ++j)
Mat[i][j] = 1;
}
~Three() {};
vector<One> get_ones(){return ones;};
vector<Two> get_twos(){return twos;};
unsigned int get_Mat(unsigned int i, unsigned int j) { return Mat[i][j];};
void set_ones(vector<One> vector_1_value) {ones = vector_1_value;};
void set_twos(vector<Two> vector_2_value) {twos = vector_2_value;};
};
///////////////////////////////////////////////////////////////////////
int main()
{
cout<< "Hello, This is a draft for classes"<< endl;
vector<One> elements(5);
cout<<elements[1].get_id()<<endl;
vector<Two> members(10);
cout<<members[8].get_One_1()<<endl;
Three item(elements, members);
cout<<item.get_ones()[3].get_id() << endl;
cout << item.get_Mat(4, 2) << endl;
return 0;
}
First, when you construct your object of class Three here:
Three item(elements, members);
its Mat member is a vector<vector<unsigned int> > of size zero. It is pure coincidence that the constructor does not crash right away. For example if you need a matrix of size n x m, you would have to do
Mat.resize(n);
for(unsigned int i =0;i<n;++i)
Mat[i].resize(m);
before you can safely use expressions like Mat[i][j].
Second, in your constructor of Three:
for(unsigned int i = 0; i < ones.size(); ++i)
for(unsigned int j = 0; j < ones.size(); ++j)
Mat[i][j] = 1;
is it intended that you don't use twos.size() in one of the loops?

Multi-threaded Simulated Annealing

I wrote a multithreaded simulated annealing program but its not running. I am not sure if the code is correct or not. The code is able to compile but when i run the code it crashes. Its just a run time error.
#include <stdio.h>
#include <time.h>
#include <iostream>
#include <stdlib.h>
#include <math.h>
#include <string>
#include <vector>
#include <algorithm>
#include <fstream>
#include <ctime>
#include <windows.h>
#include <process.h>
using namespace std;
typedef vector<double> Layer; //defines a vector type
typedef struct {
Layer Solution1;
double temp1;
double coolingrate1;
int MCL1;
int prob1;
}t;
//void SA(Layer Solution, double temp, double coolingrate, int MCL, int prob){
double Rand_NormalDistri(double mean, double stddev) {
//Random Number from Normal Distribution
static double n2 = 0.0;
static int n2_cached = 0;
if (!n2_cached) {
// choose a point x,y in the unit circle uniformly at random
double x, y, r;
do {
// scale two random integers to doubles between -1 and 1
x = 2.0*rand()/RAND_MAX - 1;
y = 2.0*rand()/RAND_MAX - 1;
r = x*x + y*y;
} while (r == 0.0 || r > 1.0);
{
// Apply Box-Muller transform on x, y
double d = sqrt(-2.0*log(r)/r);
double n1 = x*d;
n2 = y*d;
// scale and translate to get desired mean and standard deviation
double result = n1*stddev + mean;
n2_cached = 1;
return result;
}
} else {
n2_cached = 0;
return n2*stddev + mean;
}
}
double FitnessFunc(Layer x, int ProbNum)
{
int i,j,k;
double z;
double fit = 0;
double sumSCH;
if(ProbNum==1){
// Ellipsoidal function
for(j=0;j< x.size();j++)
fit+=((j+1)*(x[j]*x[j]));
}
else if(ProbNum==2){
// Schwefel's function
for(j=0; j< x.size(); j++)
{
sumSCH=0;
for(i=0; i<j; i++)
sumSCH += x[i];
fit += sumSCH * sumSCH;
}
}
else if(ProbNum==3){
// Rosenbrock's function
for(j=0; j< x.size()-1; j++)
fit += 100.0*(x[j]*x[j] - x[j+1])*(x[j]*x[j] - x[j+1]) + (x[j]-1.0)*(x[j]-1.0);
}
return fit;
}
double probl(double energychange, double temp){
double a;
a= (-energychange)/temp;
return double(min(1.0,exp(a)));
}
int random (int min, int max){
int n = max - min + 1;
int remainder = RAND_MAX % n;
int x;
do{
x = rand();
}while (x >= RAND_MAX - remainder);
return min + x % n;
}
//void SA(Layer Solution, double temp, double coolingrate, int MCL, int prob){
void SA(void *param){
t *args = (t*) param;
Layer Solution = args->Solution1;
double temp = args->temp1;
double coolingrate = args->coolingrate1;
int MCL = args->MCL1;
int prob = args->prob1;
double Energy;
double EnergyNew;
double EnergyChange;
Layer SolutionNew(50);
Energy = FitnessFunc(Solution, prob);
while (temp > 0.01){
for ( int i = 0; i < MCL; i++){
for (int j = 0 ; j < SolutionNew.size(); j++){
SolutionNew[j] = Rand_NormalDistri(5, 1);
}
EnergyNew = FitnessFunc(SolutionNew, prob);
EnergyChange = EnergyNew - Energy;
if(EnergyChange <= 0){
Solution = SolutionNew;
Energy = EnergyNew;
}
if(probl(EnergyChange ,temp ) > random(0,1)){
//cout<<SolutionNew[i]<<endl;
Solution = SolutionNew;
Energy = EnergyNew;
cout << temp << "=" << Energy << endl;
}
}
temp = temp * coolingrate;
}
}
int main ()
{
srand ( time(NULL) ); //seed for getting different numbers each time the prog is run
Layer SearchSpace(50); //declare a vector of 20 dimensions
//for(int a = 0;a < 10; a++){
for (int i = 0 ; i < SearchSpace.size(); i++){
SearchSpace[i] = Rand_NormalDistri(5, 1);
}
t *arg1;
arg1 = (t *)malloc(sizeof(t));
arg1->Solution1 = SearchSpace;
arg1->temp1 = 1000;
arg1->coolingrate1 = 0.01;
arg1->MCL1 = 100;
arg1->prob1 = 3;
//cout << "Test " << ""<<endl;
_beginthread( SA, 0, (void*) arg1);
Sleep( 100 );
//SA(SearchSpace, 1000, 0.01, 100, 3);
//}
return 0;
}
Please help.
Thanks
Avinesh
As leftaroundabout pointed out, you're using malloc in C++ code. This is the source of your crash.
Malloc will allocate a block of memory, but since it was really designed for C, it doesn't call any C++ constructors. In this case, the vector<double> is never properly constructed. When
arg1->Solution1 = SearchSpace;
Is called, the member variable "Solution1" has an undefined state and the assignment operator crashes.
Instead of malloc try
arg1 = new t;
This will accomplish roughly the same thing but the "new" keyword also calls any necessary constructors to ensure the vector<double> is properly initialized.
This also brings up another minor issue, that this memory you've newed also needs to be deleted somewhere. In this case, since arg1 is passed to another thread, it should probably be cleaned up like
delete args;
by your "SA" function after its done with the args variable.
While I don't know the actual cause for your crashes I'm not really surprised that you end up in trouble. For instance, those "cached" static variables in Rand_NormalDistri are obviously vulnerable to data races. Why don't you use std::normal_distribution? It's almost always a good idea to use standard library routines when they're available, and even more so when you need to consider multithreading trickiness.
Even worse, you're heavily mixing C and C++. malloc is something you should virtually never use in C++ code – it doesn't know about RAII, which is one of the few intrinsically safe things you can cling onto in C++.

Something wrong in c++ code

Please what wrong in this code:
#include <iostream>
#include <vector>
unsigned __int32 ConvertToChars(std::vector<int> container, char** pChars)
{
*pChars = (char*)&container[0];
return container.size() * sizeof(int);
}
void ConvertToIntegers(char* chars, short size, std::vector<int>& container)
{
int count = size / sizeof(int);
int* pIntegers = (int*)chars;
for(int i=0; i < count; ++i)
{
container.push_back(*(pIntegers++));
}
}
void Print(const std::vector<int>& container)
{
for(int i=0; i < container.size(); ++i)
{
std::cout << container[i] << std::endl;
}
}
void main()
{
std::vector<int> vec1;
vec1.push_back(1);
vec1.push_back(2);
vec1.push_back(3);
char* buffer = 0;
short bufferSize = ConvertToChars(vec1, &buffer);
std::vector<int> vec2;
ConvertToIntegers(buffer, bufferSize, vec2);
Print(vec2);
char c;
std::cin >> c;
}
function Print prints values:
-572662307
-842150451
-572662307
Thank you!!!
You're copying the container when you pass it to ConvertToChars, then taking a pointer to one of its elements, then seeing the copy go out of scope, which invalidates your pointer.
I don't really understand the point of your program, but part of your problem is in your ConvertToIntegers function, where you make your program interpret a char * as int *.
int* pIntegers = (int*)chars;
for(int i=0; i < count; ++i)
{
container.push_back(*(pIntegers++));
}
You're interpreting the underlying bytes as int types, which could lead to the numbers you're seeing. I'm surprised you're not running into segmentation faults as this would cause you to overstep the block of the memory pointed to by the original char *.