read access violation. this was 0xCDCDCDCD - c++

I'm confused as to what I'm doing wrong? While debugging, this shows 0xcdcdcdcd {theDouble=??? }so i know my variable isnt getting stored in my mutator. How would i go about fixing this issue? Am I supposed initialize this somewhere? I am using visual studio by the way.
Thank you for the help.
int main()
{
int i = 0;
const int MAX = 4;
CLASS **object = new CLASS*[MAX];
string name = "todd";
string aString = "words";
double aDouble = 10.0;
object[i]->setDouble(aDouble);
return 0;
}
//.cpp
CLASS::Class()
{
theDouble = new double;
*theDouble = NULL;
}
CLASS::Class(double aDouble)
{
*theDouble = aDouble;
}
void CLASS::setDouble(double p)
{
*theDouble = p;
double Class::getDouble()
{return (*theDouble);}
//.h
class CLASS
{
protected:
double *theDouble;
public:
Insurance();
Insurance(double premium);
//~Insurance();
void setDouble(double p);
double getDouble();
string toString();
};`

You use CLASS, Class and Insurance in mix where you should use one name so your posted code can not compile. I replace those with IronMan.
What you see as 0xCDCDCDCD is not this pointer value but value of the pointer member theDouble. The issue comes from in constructor:
IronMan::IronMan(double aDouble)
{
*theDouble = aDouble;
}
That constructor dereferences uninitialised member variable theDouble and
since debuggers tend to fill uninitialized memory with some bytes like 0xCD you will have that as value of the pointer. Therefore you get a crash for accessing memory at such address.
One way out of it is to allocate memory for theDouble
IronMan::IronMan(double aDouble)
{
theDouble = new double(aDouble);
}
Better would be likely to avoid using pointers there at all but just have direct double data member:
protected:
double theDouble;

Related

How to access subclass in C++ [duplicate]

This question already has answers here:
How do I declare a 2d array in C++ using new?
(29 answers)
Closed 2 years ago.
I am new to C++ and would like to access the values in a subclass.
When I am trying to access the values, my program is crashing and returning stack-dump.
For example:
class test{
protected:
std::string name;
int points;
object** inventory;
public:
test(const std::string name, int points) : name(name), points(points), inventory(new object*[10]()) {
for(int i = 0; i < 10; i++) {
this->inventory[i]->setValid(false);
}
}
class object {
protected:
bool isValid;
std::string name;
int value;
public:
object(const std::string name, int value) : name(name), value(value), isValid(false) {}
const std::string getName();
bool getValid();
void setValid(bool isValid);
};
In the header file.:
void object::setValid(bool isValid) {
this->isValid = isValid;
//std::cout << isValid; returning of isValid is possible, but not of this->isValid
}
The necessary header files and declarations are included.
While debugging it stops while trying to get the value of this->isValid in my class object with the following error message:
Failed to execute MI command:
-data-evaluate-expression ((this)->isValid)
Error message from debugger back end:
Cannot access memory at address 0xc
Do I use an incorrect pointer? How can I solve the issue?
This is a pointer to a pointer to an object. You allocated an array of pointers to objects, but not the objects themselves.
object** inventory;
Once you do this:
inventory(new object*[10]())
You can now access inventory[0] through inventory[9]. But they aren't set to anything yet. They may not even be null, it's just garbage memory.
You can allocate the objects in the loop:
for(int i = 0; i < 10; i++) {
inventory[i] = new object();
inventory[i]->setValid(false);
}
But, you'll need to remember to free all of those objects. You might consider using array allocators to allocate an array of objects instead of an array of pointers to objects. But since this is C++, better to use a vector.
std::vector<object> inventory

malloc and free memory leakage

im trying to create a class which has malloc.
the class has internal struct.
the user will have pointer to the struct but he may not know about the struct or even care about it.
he must save the pointer and some functions will require the address of that struct.
so in the header of the library i did the following:
#define EELS_MAX_SLOTS 5
class EELS
{
typedef struct{
//struct difinition ...
}ee_slot_t;
public:
EELS();
uint8_t CreateSlot(uint16_t begin_addr, uint16_t length, uint8_t data_length);
~EELS();
protected:
private:
void* _slot_arr[EELS_MAX_SLOTS];
uint8_t _slot_counter;
};
and the code in the execution file:
// default constructor
EELS::EELS()
{
_slot_counter =0;
} //EELS
uint8_t EELS::CreateSlot(uint16_t begin_addr, uint16_t length, uint8_t data_length){
if (_slot_counter > EELS_MAX_SLOTS)
return NULL;
ee_slot_t* slot_p;
slot_p = malloc(sizeof(ee_slot_t))
if (!slot_p)
return NULL;
slot_p->begining = begin_addr;
slot_p->length = length;
slot_p->counter = 0; // TODO...init...
slot_p->position = 0; // TODO...init...
_slot_arr[_slot_counter] = (void*)slot_p;
_slot_counter++;
return _slot_counter;
}
// default destructor
EELS::~EELS()
{
for (int i=0; i<_slot_counter; i++)
{
free((ee_slot_t*)_slot_arr[i]);
}
}
as you can see im returning index of pointers array.. so (1-6) in this case and I'm saving the real address inside that pointers array.
but from what you see. is this safe? the free method and malloc.. there is some mistake or memory leakage?
why not vector?
because its for embedded system and the current IDE/toolchain im using doesnt support std:vectors.
What happens when _slot_counter == EELS_MAX_SLOTS.
So I think you should change the if statement
if (_slot_counter > EELS_MAX_SLOTS)
return NULL;
to
if (_slot_counter >= EELS_MAX_SLOTS)
return 0; // return type is uint8_t, not a pointer

Calling virtual method of a derived class causes segfaults

I'm trying to make a chess program, but I want to be able to implement different AIs in it. Thus I made a abstract AIgeneric class and the derived class AIrandom off of AIgeneric. Then in my chessAI interface, I create a list of the the AIs, and try to call their getNextMove function and run into a segfault. The code is as below:
class AIgeneric {
public:
virtual int getNextMove(int*, const int &) = 0;
}
class AIrandom : public AIgeneric {
public:
AIrandom();
virtual int getNextMove(int*, const int &);
}
class chessAI {
public:
chessAI();
~chessAI();
void setAI();
int getNextMove(int*, const int &);
private:
vector<AIgeneric*> AIlist;
vector<string> names;
int selectedAI;
};
chessAI::chessAI () {
AIrandom randomAI;
AIlist.push_back(&randomAI);
names.push_back("Random AI");
selectedAI = -1;
}
int chessAI::getNextMove(int * board, const int & color) {
return AIlist[selectedAI]->getNextMove(board, color); //segfault on this line
}
It'd be great if anyone could help me on this problem!
Edit: I do set selectedAI to 0 before calling getNextMove.
In this code:
chessAI::chessAI () {
AIrandom randomAI;
AIlist.push_back(&randomAI);
names.push_back("Random AI");
selectedAI = -1;
}
You store a pointer to a local variable into your vector. After the constructor returns that pointer is no longer valid.
Remember that all local variables are stored on the stack, and the stack is reused in other functions. So when you use the pointer in the vector, it now points to some other functions memory and not the one object you declared.
This can be solved in three ways:
Allocate the object on the heap:
AIlist.push_back(new AIRandom);
Not using pointers at all.
Use smart pointers, such as std::unique_ptr.
You call selectedAI = -1; and then AIlist[selectedAI]->.... What do you expect AIlist[-1] to be, other than undefined behavior?
I expect this is because AIlist[selectedAI] is out of bounds. You can confirm this by replacing it with AIlist.at(selectedAI). Keep in mind that this index is -1 immediately after the constructor...

C++ read() from ifstream: without pointers?

Suppose I have a struct and a file with binary representations of those structs and I'll make a function/method that access this binary data using ifstream::read().
Here's an example struct:
struct MyStruct {
int x; //Value interested in
int y; //Value interested in
int anotherInteger; //Not interested
double aDouble; //Not interested
}
How do I make the function (I'll call it here readData) either: not using pointers when reading or, if using pointers is necessary, where would I put the proper delete?
So far, the relevant part of my readData looks like this:
void readData(int position, int &returnX, int &returnY) {
ifstream inFile("binaryFile.dat",ios::binary);
MyStruct *st = new MyStruct[1];
inFile.seekg(sizeof(MyStruct)*pos);
inFile.read((char*) st, sizeof(MyStruct));
returnX = st[0].x;
returnY = st[0].y;
//delete [] st goes here?
}
I've tried uncommenting the delete part, but I get an allocation error, probably because the values of x and y are pointing to something that doesn't exist anymore.
Any ideas on how to solve this?
Why wouldn't you use a local variable?
void readData(int position, int &returnX, int &returnY) {
ifstream inFile("binaryFile.dat",ios::binary);
inFile.seekg(sizeof(MyStruct)*position);
MyStruct st;
inFile.read((char*) &st, sizeof(MyStruct));
returnX = st.x;
returnY = st.y;
}
int main() {
int mainx, mainy;
readData(0, mainx, mainy);
return 0;
}
Also, references cannot be re-seated. Therefore the assignment assigns the value to the origional int passed by the calling function. returnX and returnY are not pointed at the local variables. In the code above, the assignment changes mainx and mainy.
The simpler way it's to use a local variable:
void readData(int position, int &returnX, int &returnY) {
ifstream inFile("binaryFile.dat",ios::binary);
MyStruct st;
inFile.seekg(sizeof(MyStruct)*position);
inFile.read((char*)&st, sizeof(MyStruct));
returnX = st.x;
returnY = st.y;
}
The delete[] is fine. If you get an error, it's not because the values of x and y are pointing to something that doesn't exist anymore since their values are just integers and don't point to anything.

Passing pointer to 2D array c++

I'm having this problem for quite a long time - I have fixed sized 2D array as a class member.
class myClass
{
public:
void getpointeM(...??????...);
double * retpointM();
private:
double M[3][3];
};
int main()
{
myClass moo;
double *A[3][3];
moo.getpointM( A ); ???
A = moo.retpointM(); ???
}
I'd like to pass pointer to M matrix outside. It's probably very simple, but I just can't find the proper combination of & and * etc.
Thanks for help.
double *A[3][3]; is a 2-dimensional array of double *s. You want double (*A)[3][3];
.
Then, note that A and *A and **A all have the same address, just different types.
Making a typedef can simplify things:
typedef double d3x3[3][3];
This being C++, you should pass the variable by reference, not pointer:
void getpointeM( d3x3 &matrix );
Now you don't need to use parens in type names, and the compiler makes sure you're passing an array of the correct size.
Your intent is not clear. What is getpointeM supposed to do? Return a pointer to the internal matrix (through the parameter), or return a copy of the matrix?
To return a pointer, you can do this
// Pointer-based version
...
void getpointeM(double (**p)[3][3]) { *p = &M; }
...
int main() {
double (*A)[3][3];
moo.getpointM(&A);
}
// Reference-based version
...
void getpointeM(double (*&p)[3][3]) { p = &M; }
...
int main() {
double (*A)[3][3];
moo.getpointM(A);
}
For retpointM the declaration would look as follows
...
double (*retpointM())[3][3] { return &M; }
...
int main() {
double (*A)[3][3];
A = moo.retpointM();
}
This is rather difficult to read though. You can make it look a lot clearer if you use a typedef-name for your array type
typedef double M3x3[3][3];
In that case the above examples will transform into
// Pointer-based version
...
void getpointeM(M3x3 **p) { *p = &M; }
...
int main() {
M3x3 *A;
moo.getpointM(&A);
}
// Reference-based version
...
void getpointeM(M3x3 *&p) { p = &M; }
...
int main() {
double (*A)[3][3];
moo.getpointM(A);
}
// retpointM
...
M3x3 *retpointM() { return &M; }
...
int main() {
M3x3 *A;
A = moo.retpointM();
}
The short answer is that you can get a double * to the start of the array:
public:
double * getMatrix() { return &M[0][0]; }
Outside the class, though, you can't really trivially turn the double * into another 2D array directly, at least not in a pattern that I've seen used.
You could create a 2D array in main, though (double A[3][3]) and pass that in to a getPoint method, which could copy the values into the passed-in array. That would give you a copy, which might be what you want (instead of the original, modifiable, data). Downside is that you have to copy it, of course.
class myClass
{
public:
void getpointeM(double *A[3][3])
{
//Initialize array here
}
private:
double M[3][3];
};
int main()
{
myClass moo;
double *A[3][3];
moo.getpointM( A );
}
You may want to take the code in your main function which works with the 2D array of doubles, and move that into myClass as a member function. Not only would you not have to deal with the difficulty of passing a pointer for that 2D array, but code external to your class would no longer need to know the details of how your class implements A, since they would now be calling a function in myClass and letting that do the work. If, say, you later decided to allow variable dimensions of A and chose to replace the array with a vector of vectors, you wouldn't need to rewrite any calling code in order for it to work.
In your main() function:
double *A[3][3];
creates a 3x3 array of double* (or pointers to doubles). In other words, 9 x 32-bit contiguous words of memory to store 9 memory pointers.
There's no need to make a copy of this array in main() unless the class is going to be destroyed, and you still want to access this information. Instead, you can simply return a pointer to the start of this member array.
If you only want to return a pointer to an internal class member, you only really need a single pointer value in main():
double *A;
But, if you're passing this pointer to a function and you need the function to update its value, you need a double pointer (which will allow the function to return the real pointer value back to the caller:
double **A;
And inside getpointM() you can simply point A to the internal member (M):
getpointeM(double** A)
{
// Updated types to make the assignment compatible
// This code will make the return argument (A) point to the
// memory location (&) of the start of the 2-dimensional array
// (M[0][0]).
*A = &(M[0][0]);
}
Make M public instead of private. Since you want to allow access to M through a pointer, M is not encapsulated anyway.
struct myClass {
myClass() {
std::fill_n(&M[0][0], sizeof M / sizeof M[0][0], 0.0);
}
double M[3][3];
};
int main() {
myClass moo;
double (*A)[3] = moo.M;
double (&R)[3][3] = moo.M;
for (int r = 0; r != 3; ++r) {
for (int c = 0; c != 3; ++c) {
cout << A[r][c] << R[r][c] << ' ';
// notice A[r][c] and R[r][c] are the exact same object
// I'm using both to show you can use A and R identically
}
}
return 0;
}
I would, in general, prefer R over A because the all of the lengths are fixed (A could potentially point to a double[10][3] if that was a requirement) and the reference will usually lead to clearer code.