04-19-2015, 02:03 PM | #1 |
Expect delays.
Join Date: Mar 2008
Location: Montreal, QC
Age: 31
Posts: 4,119
|
Coding help
To whom may be able to lend me a hand,
I am trying to write a code for my C++ class which basically fixes the language's problem of accessing elements out of bounds for a particular buffer using classes and operator overloading. It sounds like basic stuff once you know what's what, and that's the reason why I don't understand why I'm having trouble with this. Here is my code: Code:
#include <iostream> using namespace std; // création du patron de classe template <class Type> class monTableau { private: Type *Ptr; //pointeur sur un tableau int borneInf; // borne inférieure des indices du tableau int borneSup; // borne supérieure des indices du tableau public: monTableau<Type>(int inf, int sup) // Constructeur de tableau { Ptr += inf; // Le pointeur avance (ou recule) jusqu'a la borneInf donnée par l'usager borneInf = inf; borneSup = sup; // Test si les bornes inf et sup sont en ordre croissant if (inf > sup) { cout << "Les indices du tableau doivent suivre un ordre croissant." << endl; } // Si les bornes suivent un ordre croissant, on remplit le tableau d'éléments vides else { for (int i=inf ; i < sup ; i++) { *(Ptr+i)=0; // edit: This line is supposedly a big part of the problem based on testing } } } // Surdéfinition de l'opérateur [], permet d'éviter les débordements de tableaux Type operator [] (const int n) { // Si le n demandé ne fait pas partie des indices du tableau if (n < borneInf || borneSup < n) { cout << "Débordement de tableau, ne peut pas accéder à l'élément " << n << "." << endl; } // Si on n'a pas retourné de message d'erreur, ... else { return *(Ptr + n); // ... on retourne l'élément pointé, Ptr + n } } // Surdéfinition de l'opérateur ==, compare l'élément du tableau Ptr avec l'élément visé (elem). bool operator == (const Type & elem) { if (*this == elem) {return true; cout << "test2" << endl;} else return false; } // Surdéfinition de l'opérateur !=, retourne les valeurs opposées de l'opérateur == surdéfini ci-haut. bool operator != (const Type & elem) { if(*this == elem) return false; else return true; } } ; int main() { monTableau<int> tableau1(3,5); cout << tableau1[4]; // monTableau<int> tableau2(1,2); // This line makes it seg fault // cout << (tableau1[4]==tableau1[4]) << endl; // This line also makes it seg fault return 0; } edit: im adding comments to the code as I find the problematic lines. Last edited by MarioNintendo; 04-19-2015 at 02:23 PM.. |
04-19-2015, 02:48 PM | #2 |
Expect delays.
Join Date: Mar 2008
Location: Montreal, QC
Age: 31
Posts: 4,119
|
Re: Coding help
So yeah. My issue at the moment is when I want to access what my pointer Ptr is pointing to.
*Ptr, Ptr[0] or any variation of this gets me a seg fault at the moment. Edit: well, I see that when I make *Ptr as public, the seg faults disappear. I am curious however what should be added to my code for it to work with Ptr set as private. Last edited by MarioNintendo; 04-19-2015 at 03:32 PM.. |
04-19-2015, 04:24 PM | #3 | |
Under the scarlet moon
Join Date: Jan 2014
Age: 31
Posts: 921
|
Re: Coding help
Quote:
What you should do is allocate new memory of size (sup - inf + 1) with the operator new and change the operator[] to offset the index by -inf. The boundary check is ok. Edit: Something like Code:
monTableau<Type>(int inf, int sup) : Ptr(NULL) , // Can be allocated here but it would be before boundary check borneInf(inf) , borneSup(sup) { [...] Ptr = new Type[sup-inf+1]; // Allocate memory for the array [...] } ~monTableau<Type>() { delete[] Ptr; // Must free allocated memory } Type& operator [] (const int n) { [...] return Ptr[n-borneInf]; } Last edited by AutotelicBrown; 04-19-2015 at 04:55 PM.. |
|
04-20-2015, 12:23 AM | #4 |
Expect delays.
Join Date: Mar 2008
Location: Montreal, QC
Age: 31
Posts: 4,119
|
Re: Coding help
Thanks so much. Indeed, I had beginner's problem with dynamic memory allocation with my pointers. Here's the code I ended up with, which does what I wanted it to do, if it could help anyone in the future:
One thing I intentionally omitted is the use of delete in the destructor ~monTableau. It made the pointer to freak out since, as far as I can tell, it was trying to access an outdated destination via a modified pointer. Welp. One day, I'll learn to fix that particular mistake. In the meantime, I'm off to bed. Last edited by MarioNintendo; 04-20-2015 at 12:24 AM.. |
04-20-2015, 02:32 AM | #5 |
Under the scarlet moon
Join Date: Jan 2014
Age: 31
Posts: 921
|
Re: Coding help
You have to call delete[] on the original value you get for Ptr when you call new[], but you are changing it in the following line:
Code:
Ptr += inf; // Le pointeur avance (ou recule) jusqu'a la borneInf donnée par l'usager Additionally, nelems should be borneSup-borneInf+1. There is also some best practices when implementing operator= especially if you need to allocate memory on the heap because new can throw an exception, but I guess that's beyond your current needs. |
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
Thread Tools | |
Display Modes | |
|
|