maybe creating functions load and unload would be a better idea
Printable View
maybe creating functions load and unload would be a better idea
First, let's correct some errors in your initial code:
Second, Let's try and make your class obey simple data encapsulation rulesCode:class abc {
public:
int* a;
abc() {
a = 0;
}
void func() {
a = new int[100000];
//do stuff...
}
~abc() {
delete[] a;
}
};
Now... let's do it your way...Code:class abc {
private:
int* a;
public:
abc() {
a = 0;
}
void func() {
a = new int[100000];
//do stuff...
}
~abc() {
delete[] a;
}
};
Code:class abc {
private:
int* a;
public:
abc() {
a = 0;
}
void func() {
delete[] a;
a = 0;
a = new int[100000];
//do stuff...
}
~abc() {
delete[] a;
}
};
Hmm, I think that I have found what the problem is, but I'm not sure yet. Thanks for the help everyone, but (as I'm not sure yet), I think that the preoblem for deallocation comes from the fact that I tried to allocate more than I had needed! I mean that my pointer needed like 300k of memory (100000*3bytes) but I realized that somewhere in my loops I had something like this:
But 400 000 is an address that is higher than what I had asked for, so I tried skipping that loop where I got this "over-assignation" :) and then my errors disappeared. So then, could it be possible that seeking memory farther then what we had asked for might do crashes when it comes to allocating/deleting?Code:a[400000] = ...;
I've yet to see a system where an int is 3 bytes. I've seen 2, most popular systems today are 4, but I haven't seen 3.
I would suggest something like this:
Code:class abc {
public:
int* a;
abc()
: a(0) {
}
void func() {
alloc(100000);
//do stuff...
}
~abc() {
dealloc();
}
void
alloc(unsigned n) {
dealloc();
a = new int[n];
}
void dealloc() {
delete [] a;
a = 0;
}
};
>> But 400 000 is an address that is higher than what I had asked for.
Array indexes are just that, indexes, not addresses. If you create an array with 100000 spaces, then only indexes 0 through 99999 are allowed. It doesn't matter how many bytes an int is, the valid indexes are still the same.
I was always talking about "int"s, but in fact it's true, ints don't take 3bytes, but its because I said I used ints to keep it simple, but in reality, I don't use them, I use a 3 bytes class consisted of 3 chars, so that's were all the threes come from.
But for the "array", it's not about being a "defined" array (not dynamic, NEW-ed), it's because I just used the (int again :))to represent that is was an address of type int, where we added the part of address [some_number], so it's not an array that I declared with a specific capacity...Code:int[some_number]
Sorry for all the misunderstanding I might have caused!