IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C++ Discussion :

Segmentation fault et retour de données


Sujet :

C++

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Nouveau candidat au Club
    Homme Profil pro
    Lycéen
    Inscrit en
    Mai 2011
    Messages
    2
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations professionnelles :
    Activité : Lycéen
    Secteur : Arts - Culture

    Informations forums :
    Inscription : Mai 2011
    Messages : 2
    Par défaut Segmentation fault et retour de données
    Bonjour/Bonsoir tout le monde ! J'ai posté un thread il n'y a pas très longtemps demandant des conseils pour récupérer les données de QPlainTextEdit dans une classe X, les traités et les renvoyés dans des QTextBrowser dans la classe Y. Seulement je ne vois aucun moyen de renvoyer les données dans la classe Y. J'ai essayé de nombreuses solutions mais aucune ne semble marcher. Le code qui suit est le plus récent, il compile mais ne s'exécute pas, renvoyant un signal SIGSEGV; segmentation fault. J'aimerais avoir des conseils et si possible, un ou deux snippets de code fonctionnel s.v.p . Merci d'avance !

    CrypterText.h
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
     
    #ifndef CRYPTERTEXT_H
    #define CRYPTERTEXT_H
     
    #include <QString>
    #include <QtGlobal>
    #include <QTime>
    #include <QPlainTextEdit>
    #include <QTextBrowser>
    #include <vector>
    #include "textcryptedwindow.h"
     
    class CrypterText
    {
     
    public:
        CrypterText();
        ~CrypterText();
        void cryptTheText(QString textToCrypt); // Execute the function to crypt
     
    private :
        void verifyIfCanGenerate(); // Check if we can generate the key without problem
        void generateKey(); // Function called to generate the key
        QChar oneRandomChar(); // Function to get an ASCII random char
        void convertUserTextToNumber();
        void convertKeyToNumber();
        void toNumber(QString str, std::vector<int> &vectorToInitialize); // Initialized the vector pass in reference with the ASCII value of the str
        void sumNumberBetweenThem(); // Add both ASCII value
        void checkIfNumberReachCap(); // Check if the sum of the two number bypassed 255 or 32
        void setCryptedTextFromSumValues(); // Initialized the output crypted text string with the ASCII values recovered by the vector
        void setBrowser(); // Send the data up to the browser
     
        TextCryptedWindow* theWindow;
     
        QString inputTextToCrypt; // The text entered by the user that need to be crypt
        QString outputKeytoDecrypt; // The key that the generator will create to encrypt and decrypt the text entered by the user
        QString outputCryptedText; // The text encrypted by the key
        std::vector<int> ASCIIValueOfTheKey; // A vector who stocks the ASCII values of each key's characters
        std::vector<int> ASCIIValueOfTheUncryptedText; // A vector who stocks the ASCII values of each input user text characters;
        std::vector<int> sumOfBothKeyAndTextASCIIValues; // A vector who stocks the sums of the ASCII values of both input text and output key
    };
     
    #endif // CRYPTERTEXT_H
    CrypterText.cpp

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
     
    #include "crypterText.h"
     
    CrypterText::CrypterText(){
        theWindow = new TextCryptedWindow();
    }
     
    void CrypterText::cryptTheText(QString textToCrypt) {
        inputTextToCrypt = textToCrypt; // Get the input to work with
        verifyIfCanGenerate(); // check if it's necessary to generate a key
        convertUserTextToNumber(); // Convert the user input text to crypt to his ASCII values
        convertKeyToNumber(); // Same thing except we work on the key
        sumNumberBetweenThem(); // Add the ASCII values of the key and the ASCII values of the text between them
        checkIfNumberReachCap(); // Check if the number doesn't overflow or underflow
        setCryptedTextFromSumValues(); // Change the number to the ASCII letters corresponding
        setBrowser(); // Send the information to the window
    }
     
    void CrypterText::verifyIfCanGenerate(){
        if(outputKeytoDecrypt.size() < inputTextToCrypt.size()) // Check if the key isn't the same lenght as the text
            generateKey(); // We can generate a key
    }
     
    void CrypterText::generateKey(){
        for(int i = 0; i < inputTextToCrypt.size(); i++)
            outputKeytoDecrypt += oneRandomChar(); // Until the key is the same lenght as the input text, we add a random character
    }
     
    QChar CrypterText::oneRandomChar(){
        qsrand(QTime::currentTime().msec()); //Seed setup for QRand();
        return static_cast<QChar>(qrand() % (255-32+1)+32); // Return a random ASCII character
    }
     
    void CrypterText::convertUserTextToNumber(){
        toNumber(inputTextToCrypt, ASCIIValueOfTheUncryptedText); // Convert text to number
    }
     
    void CrypterText::convertKeyToNumber(){
        toNumber(outputKeytoDecrypt, ASCIIValueOfTheKey); // Convert key to number
    }
     
    void CrypterText::toNumber(QString str, std::vector<int> &vectorToInitialize){ // Fill a vector with the ASCII values
        for(int i = 0; i<str.size(); i++)
            vectorToInitialize.push_back(str[i].toAscii());
    }
     
    void CrypterText::sumNumberBetweenThem(){
        for(int i = 0; i<inputTextToCrypt.size(); i++)
            sumOfBothKeyAndTextASCIIValues[i] = ((ASCIIValueOfTheKey[i]) + (ASCIIValueOfTheUncryptedText[i]));
    }
     
    void CrypterText::checkIfNumberReachCap(){
        for(int i = 0; i<sumOfBothKeyAndTextASCIIValues.size(); i++){
            if(sumOfBothKeyAndTextASCIIValues[i] > 255)
                sumOfBothKeyAndTextASCIIValues[i] -= 255;
            if(sumOfBothKeyAndTextASCIIValues[i] < 32)
                sumOfBothKeyAndTextASCIIValues[i] += 255;
        }
    }
     
    void CrypterText::setCryptedTextFromSumValues(){
        for(int i = 0; i < sumOfBothKeyAndTextASCIIValues.size(); i++)
            outputCryptedText += static_cast<QChar>(sumOfBothKeyAndTextASCIIValues[i]);
    }
     
    void CrypterText::setBrowser(){
        (*theWindow).sendCryptedTextToBrowserOutput(outputCryptedText);
        (*theWindow).sendKeyToBrowserOutput(outputKeytoDecrypt);
    }
     
    CrypterText::~CrypterText(){
        delete theWindow;
    }
    TextCryptedWindow.h

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
     
    #ifndef TEXTCRYPTEDWINDOW_H
    #define TEXTCRYPTEDWINDOW_H
     
    #include <QMainWindow>
    #include <QWidget>
    #include <QTime>
    #include <QtGlobal>
    #include <vector>
    #include "ui_textcryptedwindow.h"
     
    class CrypterText;
     
    class TextCryptedWindow : public QMainWindow, private Ui::TextCryptedWindow
    {
        Q_OBJECT
     
    public:
        TextCryptedWindow();
        ~TextCryptedWindow();
        QString getTextInputFromUserToCrypt();
        QString getKeyInputToDecrypt();
        QString getTextInputToDecrypt();
        void sendKeyToBrowserOutput(QString dataToSend);
        void sendCryptedTextToBrowserOutput(QString dataToSend);
        void sendDecryptedTextToBrowserOutput(QString dataToSend); // To add to decrypter window
     
    public slots :
        void callTheCrypter();
     
    private slots:
        void decrypIt();
        void arrangeKey();
     
    private:
        void setConnection();
        void substractKeyAndText();
     
        CrypterText* theCrypter;
     
        QString inputKeyDecrypt;
        QString inputStringDecrypt;
        QString outputStringDecrypt;
        std::vector<int> inputCryptedTextValueVector;
        std::vector<int> inputKeyValueVector;
    };
     
    #endif // TEXTCRYPTEDWINDOW_H
    TextCrypted.cpp
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
     
    #include "crypterText.h"
     
    using namespace std;
     
    TextCryptedWindow::TextCryptedWindow()
    {
        theCrypter = new CrypterText();
        setupUi(this);
        setConnection();
    }
     
    void TextCryptedWindow::setConnection(){
        connect(buttonCrypt, SIGNAL(clicked()), this, SLOT(callTheCrypter())); // Connect the button to the crypter
    }
     
    void TextCryptedWindow::callTheCrypter(){ // Call the crypter with the text entered by the user
        (*theCrypter).cryptTheText(inputText->toPlainText());
    }
     
    void TextCryptedWindow::sendCryptedTextToBrowserOutput(QString dataToSend){ // Send the crypted text up to the browser
        outputCryptedText->setText(dataToSend);
    }
     
    void TextCryptedWindow::sendDecryptedTextToBrowserOutput(QString dataToSend){ // Send to decrypted text up to the browser
        outputDecryptedText->setText(dataToSend);
    }
     
    void TextCryptedWindow::sendKeyToBrowserOutput(QString dataToSend){ // Send the key up to the browser
        outputKey->setText(dataToSend);
    }
     
    void TextCryptedWindow::arrangeKey(){
        // Clear the key
    }
     
    void TextCryptedWindow::decrypIt(){
        substractKeyAndText();
    }
     
    void TextCryptedWindow::substractKeyAndText(){
        for(int i = 0; i < inputStringDecrypt.size(); i++)
            outputStringDecrypt += (inputCryptedTextValueVector[i] - inputKeyValueVector[i]);
    }
     
    TextCryptedWindow::~TextCryptedWindow(){
        delete theCrypter;
    }

  2. #2
    Rédacteur
    Avatar de 3DArchi
    Profil pro
    Inscrit en
    Juin 2008
    Messages
    7 634
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2008
    Messages : 7 634
    Par défaut
    Salut,
    Pour la recherche plus précise de ton problème, je dirais, affines avec un debugger (ou au pire avec des traces).
    Je ne vois rien d'évident dans ton code (même si d'autres points me gênent).
    Dans le contexte que tu décris et au vu du code, l'erreur 'segmentation fault' est souvent due à l'utilisation d'une variable libérée. Soit un des pointeurs de tes classes qui a été libéré à tort (cf Gérer ses ressources de manière robuste en C++ par Aurélien Regat-Barrel et Présentation des pointeurs intelligents en C++ par Loïc Joly) ou trop tôt. Soit tu retournes une variable locale par référence. Soit un pointeur initialisé avec une variable locale et utilisé au delà de la durée de vie de la variable.

  3. #3
    Nouveau candidat au Club
    Homme Profil pro
    Lycéen
    Inscrit en
    Mai 2011
    Messages
    2
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations professionnelles :
    Activité : Lycéen
    Secteur : Arts - Culture

    Informations forums :
    Inscription : Mai 2011
    Messages : 2
    Par défaut
    Merci pour les pistes. J'irai lire les liens que tu m'as donné qui me semble bien intéressant (surtout les pointeurs intelligents dont j'ai souvent entendu parler) !

  4. #4
    Membre émérite

    Profil pro
    Inscrit en
    Décembre 2008
    Messages
    533
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2008
    Messages : 533
    Par défaut
    Ligne 43 de TextCrypted.cpp tu es bien sûr que tes 2 vector inputCryptedTextValueVector et inputKeyValueVector ont un élément i ?

    Pour vérifier :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    inputCryptedTextValueVector.at(i) - inputKeyValueVector.at(i)
    Si c'est bien le problème, tu devrais avoir une exception au lieu d'une SIGSEGV.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Pb segmentation fault avec glutinit()
    Par pipistrelle dans le forum GLUT
    Réponses: 2
    Dernier message: 17/11/2004, 23h17
  2. [SDL_Image] Img_Load : segmentation fault ....
    Par Mathieu.J dans le forum OpenGL
    Réponses: 6
    Dernier message: 19/10/2004, 23h52
  3. [REDHAT] Segmentation fault systematique
    Par mela dans le forum RedHat / CentOS / Fedora
    Réponses: 2
    Dernier message: 21/09/2004, 06h05
  4. Réponses: 13
    Dernier message: 13/07/2004, 15h41
  5. Comment contrer la "segmentation fault" ?
    Par guillaume_pfr dans le forum C
    Réponses: 15
    Dernier message: 08/08/2003, 13h43

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo