When I run my program with valgrind it gives an invalid read and write of size 8 error. I have broke my head over this but I can't see what's going wrong.
The valgrind errors occur in the last and second last lines of this code:
void MLPerceptron::returnOutputActivation(vector<Feature> imageFeatures,vector<double>& outputActivation){
int train = 1;
for (unsigned int i = 0; i<imageFeatures.size();i++){
activations[0] = imageFeatures[i].content;
feedforward(train);
activationsToOutputProbabilities();
setMinActivation(outputActivation,activations[2]);
}
}
void MLPerceptron::setMinActivation(vector<double>& minOutputActivation,vector<double> currentActivation){
for(unsigned int i=0;i<currentActivation.size();i++){
if(minOutputActivation[i] > currentActivation[i])
minOutputActivation[i] = currentActivation[i];
}
}
The vectors are initialized in another function and then given to the function returnOutputActivations, this happens in a different file see here:
void MLPController:: createOutputProbabilitiesVectorTest(vector<vector<Feature> >& testSet){
unsigned int nOutputProbabilities = settings.mlpSettings.nOutputUnits;
vector<double> input;
input.reserve(nOutputProbabilities*nMLPs);
for(int j=0; j<nMLPs; j++){
vector<Feature>::const_iterator first = testSet[j].begin();
vector<Feature>::const_iterator last = testSet[j].begin()+numPatchesPerSquare[j];
vector<double> inputTemp = vector<double>(nOutputProbabilities, 10.0);
mlps[0][j].returnOutputActivation(vector<Feature>(first,last),inputTemp);
input.insert(input.end(),inputTemp.begin(),inputTemp.end());
}
Feature newFeat = new Feature(input);
newFeat.setLabelId(testSet[0][0].getLabelId());
inputTrainSecondLayerMLP.push_back(newFeat);
}
I know that there already a lot of posts about the valgrind error but it didn't help me to figure out what's going wrong.
I think
Feature newFeat = new Feature(input)
is the problem. This will allocate a new Feature on the heap, but you will lose its address and it will thus not be deleted. Use Feature* newFeat = new Feature(input) as per MikeCAT's suggestion.
Related
I'm working on a school assignment. It is an assignment in which every 2 weeks, we have to either expand or change the layout of it. This week, we are forced to use pointers. I'm having a hard time understanding memory and how to allocate it properly without having segmentation faults.
I've created a struct array which is initialized to a char pointer. Every time i loop, after the 1st loop i get "segmentation faults". I simply don't understand why?
I could include the whole code but according to gdb my issue is pertaining to 1 specific line.
const int arraySize = 100;
int counter = 0;
struct contacts{
char * name;
char * date;
char * note;
};
contacts * contactList[arraySize] =
contactList = new contacts;
for(int i = 0; i <= counter; i++){
contactList[i]->name = new char[20]; //Segmentation Fault here
std::cout << contactList[i]->name << std::endl;
//first 1 outputs = fine
//2nd output = segmentation error
counter++;
}
The code is simplified and minimilized for easy reading. If anyone wants it i can insert the whole code. Just be wary that is relatively big. I have set breakpoint through my code to narrow it down. It has come down to that specific statement. Everything else i perfectly fine, especially since it all compiles perfectly fine.
Any hints or assistance with it can be great.
Also I'm not allowed to use any vectors, strings, etc., only cstrings.
User mentioned that i only create 1 contact.
contacts * contactList[arraySize];
contactList = new contacts;
//Instead it should be like this:
contacts * contactList[arraySize];
contactList = new contacts[arraySize];
Update:
I've tried using what everyone recommended.
contacts* contactList[arraySize];
contactList = new contacts[arraySize];
But i get this error:
error: incompatible types in assignment of‘ContactClass::contacts*’ to ‘ContactClass::contacts* [100]’
Your first problem is in this line:
contacts * contactList[arraySize] = new contacts;
it should be
contacts* contactList = new contacts[arraySize];
next problem is here
for(int i = 0; i <= counter; i++){
should be
for(int i = 0; i < arraysize; i++){
contactList[i].name = new char[20];
}
I am getting Segmentation fault: 11 error when trying to run my program (I'm quite a n00b with c++ so take it easy on me). I know it has something to do with memory allocation but I'm not sure what exactly I am doing wrong. Can anyone please help and spot the problem/s?
Basically I'm trying to chop one vector into many small vectors, and analyse each one separately.
std::vector<double> test::getExactHit(std::vector<double> &hitBuffer, double threshold){
int resolution = 100;
int highestRMSBin = 0;
std::vector<double> exactHit(8192);
double* rmsInEachBin = new double[hitBuffer.size()/resolution];
double highestRMSValue = threshold;
for(int i = 0; i<hitBuffer.size()-resolution; i+=resolution){
std::vector<double>::const_iterator first = hitBuffer.begin() + i;
std::vector<double>::const_iterator last = hitBuffer.begin() + i + resolution;
std::vector<double> hitBufferBin(first, last);
rmsInEachBin[i/resolution] = calcRMS(hitBufferBin);
if(rmsInEachBin[i/resolution]>highestRMSValue){
highestRMSValue = rmsInEachBin[i/resolution];
highestRMSBin = i;
}
}
for(int j = 0 ; j < exactHit.size(); j++) {
exactHit[j]=hitBuffer[j+highestRMSBin];
}
return exactHit;
}
Please deallocate all the memory assigned using new or else it will cause memory leak and other bugs also might get introduced because of this .
http://cs.baylor.edu/~donahoo/tools/gdb/tutorial.html
You can debug using GDB , It will be handy to know a debugger if you are programming in C++ .
Hope this info will help you .
I have a chunk of code:
void split(std::vector<std::string> * v,const char* s,const char* x) {
size_t len = strlen(s);
size_t slen = strlen(x); //slen = Search Length
if(len==0||slen==0)
return;
v->clear();
char* f = new char[len];
memset(f,0,len);
int * counter =new int;
(*counter)=0;
for(unsigned int i = 0; i<len; i++) {
if(isNext((s+(i*sizeof(char*))),x)) {
f[i]=1;
counter++;
}
}
if((*counter)==0) {
delete [] f;
delete counter;
v->clear();
return;
}
...
However when I am debugging it with gdb (on cygwin) or the visual studio debugger I get this error (from the cygwin console)
(gdb) step
36 if(len==0||slen==0)
(gdb) step
38 v->clear();
(gdb) step
std::vector<std::string, std::allocator<std::string> >::clear (
this=0x60003a3e0)
at /usr/lib/gcc/x86_64-pc-cygwin/4.8.2/include/c++/bits/stl_vector.h:1126
1126 { _M_erase_at_end(this->_M_impl._M_start); }
(gdb)
No matter where I compile it I get the same error! When I check the values of all the variables within gdb everything is correct (values are exactly what they should be). The vector does work because I intialize it in main(), use it and then delete it and reallocate it (all without issue). Am I missing some big thing here? Googling and debugging for hours didn't seem to bring up anything. Any help is appreciated!
There's a lot here that can be simplified, but as far as major problems there is this:
int * counter =new int;
(*counter)=0;
counter++;
The counter++ is incrementing the pointer not the value pointed to. I don't see any reason why this needs to be a pointer and should probably be avoided as it just adds complexity to this.
What does isNext do? There definitely a lot you can do to simply this and when that's done it will likely reduce problems.
What are you passing to split? If the vector is uninitialized the call to ->clear() could cause an access violation.
As above, I'm trying to create and then fill an array of structures with some starting data to then write to/read from.
I'm still writing the cache simulator as per my previous question:
Any way to get rid of the null character at the end of an istream get?
Here's how I'm making the array:
struct cacheline
{
string data;
string tag;
bool valid;
bool dirty;
};
cacheline **AllocateDynamicArray( int nRows, int nCols)
{
cacheline **dynamicArray;
dynamicArray = new cacheline*[nRows];
for( int i = 0 ; i < nRows ; i++ )
dynamicArray[i] = new cacheline [nCols];
return dynamicArray;
}
I'm calling this from main:
cacheline **cache = AllocateDynamicArray(nooflines,noofways);
It seems to create the array ok, but when I try to fill it I get memory errors, here's how I'm trying to do it:
int fillcache(cacheline **cache, int cachesize, int cachelinelength, int ways)
{
for (int j = 0; j < ways; j++)
{
for (int i = 0; i < cachesize/(cachelinelength*4); i++)
{
cache[i][ways].data = "EMPTY";
cache[i][ways].tag = "";
cache[i][ways].valid = 0;
cache[i][ways].dirty = 0;
}
}
return(1);
}
Calling it with:
fillcache(cache, cachesize, cachelinelength, noofways);
Now, this is the first time I've really tried to use dynamic arrays, so it's entirely possible I'm doing that completely wrong, let alone when trying to make it 2d, any ideas would be greatly appreciated :)
Also, is there an easier way to do write to/read from the array? At the moment (I think) I'm having to pass lots of variables to and from functions, including the array (or a pointer to the array?) each time which doesn't seem efficient?
Something else I'm unsure of, when I pass the array (pointer?) and edit the array, when I go back out of the function, will the array still be edited?
Thanks
Edit:
Just noticed a monumentally stupid error, it should ofcourse be:
cache[i][j].data = "EMPTY";
You should find your happiness. You just need the time to check it out (:
The way to happiness
I am new to C++ and working with STL container at the moment.
I got a serious problem executing a nodeStack.push(startnode) - the compiler shows up a
Critical error detected c0000374
Followign code shows the function where the mentioned error occurs:
vector<int> Graph::iterativeDepthSearch(map<int, vector<int>> adjlist, int startnode) {
stack<int> nodeStack;
vector<int> visitList;
// Knotenbesuchsliste initialisieren
int* val = new int(adjlist.size());
for (int i = 0; i < (int) adjlist.size(); i++) {
val[i] = 0;
}
int cnt = 1;
nodeStack.push(startnode);
....
}
The error occurs in the line nodeStack.push(startnode);, startnode is initialized with 0.
try int* val = new int[adjlist.size()]; you are currently allocating a single int and initializing its value, not allocating an array of ints.
The stack structure is corrupting because it is next to your pointer in the memory stack.
nodeStack.push isn't really your problem. You are declaring int* val - a pointer to int, then initializing the integer at val with the size of the list. You really want
int *val = new int[adjlist.size()];
It's possible that you are using an x86 DLL; when I got this error in VS4.5, I changed my target platform to x86 and switched to .Net 4.0. That worked for me.