Torna indietro   Hardware Upgrade Forum > Software > Programmazione

realme C100x, lo smartphone economico con la batteria da 7500 mAh. La recensione
realme C100x, lo smartphone economico con la batteria da 7500 mAh. La recensione
realme C100x scommette tutto, forse troppo, sulla batteria da 7500 mAh e sulla certificazione ArmorShell per farsi notare nella fascia più economica del mercato: lo abbiamo messo alla prova per capire a chi è rivolto questo smartphone che sacrifica un po' prestazioni, display e fotocamera per offrire l'autonomia migliore possibile a un prezzo decisamente contenuto
Star Wars Zero Company è l'erede di XCOM 2
Star Wars Zero Company è l'erede di XCOM 2
Bit Reactor porta nell’universo di Star Wars una struttura tattica che richiama apertamente XCOM 2, ma la arricchisce con legami tra i personaggi, progressione ruolistica, gestione della base e un sistema di combattimento costruito attorno a tre Punti Azione e alle risorse condivise della squadra
Test ride Can-Am Origin: la moto elettrica che fa dimenticare il motore a scoppio (ma occhio all'autonomia)
Test ride Can-Am Origin: la moto elettrica che fa dimenticare il motore a scoppio (ma occhio all'autonomia)
Abbiamo provato per una settimana intera la Can-Am Origin, la Dual Sport elettrica del gruppo canadese BRP: ecco com'è andata tra città, autostrada e un primo assaggio di sterrato
Tutti gli articoli Tutte le news

Vai al Forum
Rispondi
 
Strumenti
Old 22-08-2020, 16:31   #1
Osyriis_
Junior Member
 
Iscritto dal: Aug 2020
Messaggi: 3
[C] Segmentation Fault

Salve! Spero di aver aperto la discussione in modo giusto. Ho bisogno di aiuto.
Dunque sto implementando un Binary Search Tree con inserimento e ricerca, e fin qui tutto bene, dopo di che mi è stato chiesto di implementare anche una versione modificata della ricerca che dovrebbe stampare a video tutti i numeri presenti nell'albero compresi fra k1 e k2(valori forniti dall'utente in input). Ora il problema è proprio qui, a un certo punto va in segmentation fault ma non riesco a capire quale sia il problema in quanto il codice è identico allo pseudocodice fornito. Vi metto qui di seguito il pezzo di codice in questione(chiedo scusa nel caso fosse molto ma continua a sbucarmi il segmentation sempre in un punto diverso).

Codice:
void withinRange(BST **root, int k1, int k2){
    BST *x = (BST*)malloc(sizeof(BST));
    BST *y = (BST*)malloc(sizeof(BST));
    if(k1 == k2){
        printf("%d\n", k1);
        return;
    }
    *x = BSTsearch(&root, k1);
    *y = BSTsearch(&root, k2);
    printf("%d\n", x->data);
    while(!found){
        inOrderTreeWalkWithCheck(&root, x->right, y);
        *x = treeSuccessorAsAncestor(&root, x);
        if ( x == y ){
            found = 1;
        }
        if ((x != NULL) && (!found)){
            printf("%d\n", x->data);
        }
    }
    printf("%d\n", y->data);
    found = 0;
}

void inOrderTreeWalkWithCheck(BST **root, BST *x, BST *y){
    if (x != NULL){
        if(x == y){
            inOrderTreeWalk(y);
            found = 1;
            return;
        }
    }else{
        inOrderTreeWalkWithCheck(&root, x->left, y);
        if(!found){
            printf("%d\n", x->data);
            inOrderTreeWalkWithCheck(&root, x->right, y);
        }
    }
}

void inOrderTreeWalk(BST *y){
    if(y != NULL){
        inOrderTreeWalk(y->left);
        printf("%d\n", y->data);
        inOrderTreeWalk(y->right);
    }
}

BST treeSuccessorAsAncestor(BST **root, BST *x){
    BST *y = (BST*)malloc(sizeof(BST));
    y = x->parent;
    while ((y != NULL) && (x == y->right)){
        x = y;
        y = y->parent;
    }
    return *y;
}
attualmente si blocca al while della funzione treeSuccessorAsAncestor, ho provato a modificare le condizioni ma nulla.
Osyriis_ è offline   Rispondi citando il messaggio o parte di esso
Old 23-08-2020, 18:14   #2
wingman87
Senior Member
 
Iscritto dal: Nov 2005
Messaggi: 2794
Scusa ma non ho avuto tempo di analizzare fino in fondo tutto il codice, ti scrivo quello che ho notato.

Nel metodo inOrderTreeWalkWithCheck accedi agli attributi di x nel ramo else in cui x è sicuramente NULL.

Note a parte non legate al segmentation fault:
* Ci sono dei malloc ma non ci sono free, quindi si creano dei memory leak.
* Ci sono delle variabili globali (found), e questo rende difficile seguire il flusso.
wingman87 è offline   Rispondi citando il messaggio o parte di esso
Old 24-08-2020, 07:34   #3
Kaya
Senior Member
 
Iscritto dal: Apr 2005
Messaggi: 3302
Un altro consiglio: COMMENTA.
Metti i commenti al codice che per quanto possa sembrare banale torna sempre utile quando poi ci metti mano..
Kaya è offline   Rispondi citando il messaggio o parte di esso
Old 26-08-2020, 15:55   #4
Osyriis_
Junior Member
 
Iscritto dal: Aug 2020
Messaggi: 3
Quote:
Originariamente inviato da wingman87 Guarda i messaggi
Scusa ma non ho avuto tempo di analizzare fino in fondo tutto il codice, ti scrivo quello che ho notato.

Nel metodo inOrderTreeWalkWithCheck accedi agli attributi di x nel ramo else in cui x è sicuramente NULL.

Note a parte non legate al segmentation fault:
* Ci sono dei malloc ma non ci sono free, quindi si creano dei memory leak.
* Ci sono delle variabili globali (found), e questo rende difficile seguire il flusso.
Ho corretto l'else in inOrderTreeWalkWithCheck che chiaramente andava con if (x == y), ora mi da segmentation fault su x->left della prima chiamata ricorsiva all'interno dell'else.

Per quanto riguarda i malloc aggiungo immediatamente i free che ho completamente scordato.
Found mi è stata richiesta come una variabile globale settata a 0, che comunque viene usata per la prima volta all'interno di withinrange
Osyriis_ è offline   Rispondi citando il messaggio o parte di esso
Old 27-08-2020, 08:22   #5
wingman87
Senior Member
 
Iscritto dal: Nov 2005
Messaggi: 2794
BST come è definito? Puoi riportare tutto il codice aggiornato?
wingman87 è offline   Rispondi citando il messaggio o parte di esso
Old 28-08-2020, 20:34   #6
Osyriis_
Junior Member
 
Iscritto dal: Aug 2020
Messaggi: 3
Quote:
Originariamente inviato da wingman87 Guarda i messaggi
BST come è definito? Puoi riportare tutto il codice aggiornato?

E' un po' lungo, spero non sia un problema.
Ho anche scoperto che se inserisco k1 e k2 uguali il programma va senza problemi, va in segmentation sono quando sono diversi.

Codice:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>

#define NUMOP 500

int found = 0;

typedef struct BST{
	int data;
	struct BST* parent;
	struct BST* left;
	struct BST* right;
} BST;

BST* root = NULL;

BST newNode(int value);
BST BSTinsert(BST **root, int value);
BST BSTsearch(BST *x, int value);
void withinRange(BST **root, int k1, int k2);
void inOrderTreeWalkWithCheck(BST **root, BST *x, BST *y);
void inOrderTreeWalk(BST *y);
BST treeSuccessorAsAncestor(BST **root, BST *x);

int main(){
    clock_t start, end;
    int iterazione, k1, k2, i;
    double BST=0, BSTS=0, BSTW=0;
    double mediaBST;
    FILE * risultatiBST;

    srand(1);

    risultatiBST=fopen("risultatiBST.txt","w");
	if (risultatiBST==NULL)
	{
        printf ("ERRORE nell'apertura del file");
        return(1);
	}

    printf ("Inserisci k1: ");
    scanf ("%d", &k1);
    printf("Inserisci k2:");
    scanf("%d", &k2);
    printf ("BST\n");

    int inserimento, ricerca, withinrange;
    for(i = 1; i<=NUMOP; i++){
        inserimento=(70*NUMOP)/100;
        start = clock();
        for (iterazione = 1; iterazione <= inserimento; iterazione++){
            int value = rand();
            BSTinsert(&root, value);
            //end = clock();
        }

        ricerca = (15*NUMOP)/100;
        for(iterazione = 1; iterazione<=ricerca; iterazione++){
            //start = clock();
            int value = rand();
            BSTsearch(&root, value);
            //end = clock();
            //BSTS = BSTS + (double) (end-start)/CLOCKS_PER_SEC;
        }

        withinrange = (15*NUMOP)/100;
        for(iterazione = 1; iterazione <= withinrange; iterazione++){
            //start = clock();
            withinRange(&root, k1, k2);
            //BSTW = BSTW + (double) (end-start)/CLOCKS_PER_SEC;
        }
        end = clock();
        BST = BSTW + (double) (end-start)/CLOCKS_PER_SEC;

        mediaBST=BST/NUMOP;
        printf ("%d\t %f\n",i, mediaBST);
        fprintf(risultatiBST,"%d\t %f\n", i, mediaBST);
    }

    fclose(risultatiBST);

}

BST newNode(int value){
    BST *temp = (BST*)malloc(sizeof(BST));

    temp->data = value;

    temp->left = NULL;
    temp->right = NULL;
    free(temp);
    return *temp;
}

// A utility function to insert a new
// Node with given key in BST
BST BSTinsert(BST **root, int value)
{
    // Create a new Node containing
    // the new element
    BST *newnode = (BST*)malloc(sizeof(BST));
    *newnode = newNode(value);

    // Pointer to start traversing from root and
    // traverses downward path to search
    // where the new node to be inserted
    BST *x = root;

    // Pointer y maintains the trailing
    // pointer of x
    BST *y = NULL;

    while (x != NULL) {
        y = x;
        if (value < x->data)
            x = x->left;
        else
            x = x->right;
    }

    // If the root is NULL i.e the tree is empty
    // The new node is the root node
    if (y == NULL)
        y = newnode;

    // If the new key is less then the leaf node key
    // Assign the new node to be its left child
    else if (value < y->data)
        y->left = newnode;

    // else assign the new node its right child
    else
        y->right = newnode;

    // Returns the pointer where the
    // new node is inserted
    return *y;
}

BST BSTsearch(BST *x, int value){
	if ((x == NULL) || (x->data = value)){
        return *x;
	}
	if(value<x->data){
        return BSTsearch(x->left, value);
    }else{
        return BSTsearch(x->right, value);
    }
}


//withinRange
void withinRange(BST **root, int k1, int k2){
    BST *x = (BST*)malloc(sizeof(BST));
    BST *y = (BST*)malloc(sizeof(BST));
    if(k1 == k2){
        printf("%d\n", k1);
        return;
    }
    *x = BSTsearch(&root, k1);
    *y = BSTsearch(&root, k2);
    printf("%d\n", x->data);
    while(!found){
        inOrderTreeWalkWithCheck(&root, x->right, y);
        *x = treeSuccessorAsAncestor(&root, x);
        if ( x == y ){
            found = 1;
        }
        if ((x != NULL) && (!found)){
            printf("%d\n", x->data);
        }
    }
    printf("%d\n", y->data);
    found = 0;
    free(x);
    free(y);
}

void inOrderTreeWalkWithCheck(BST **root, BST *x, BST *y){
    if (x != NULL){
        if(x == y){
            inOrderTreeWalk(y);
            found = 1;
            return;
        }else{
            inOrderTreeWalkWithCheck(&root, x->left, y);
            if(!found){
                printf("%d\n", x->data);
                inOrderTreeWalkWithCheck(&root, x->right, y);
            }
        }
    }
}

void inOrderTreeWalk(BST *y){
    if(y != NULL){
        inOrderTreeWalk(y->left);
        printf("%d\n", y->data);
        inOrderTreeWalk(y->right);
    }
}

BST treeSuccessorAsAncestor(BST **root, BST *x){
    BST *y = (BST*)malloc(sizeof(BST));
    y = x->parent;
    while ((y != NULL) && (x == y->right)){
        printf("ciao");
        x = y;
        y = y->parent;
    }
    free(y);
    return *y;
}

Ultima modifica di Osyriis_ : 28-08-2020 alle 20:44.
Osyriis_ è offline   Rispondi citando il messaggio o parte di esso
Old 28-08-2020, 21:23   #7
Lampo89
Member
 
L'Avatar di Lampo89
 
Iscritto dal: Dec 2006
Messaggi: 33
Quote:
Originariamente inviato da Osyriis_ Guarda i messaggi
E' un po' lungo, spero non sia un problema.
Ho anche scoperto che se inserisco k1 e k2 uguali il programma va senza problemi, va in segmentation sono quando sono diversi.

Codice:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>

#define NUMOP 500

int found = 0;

typedef struct BST{
	int data;
	struct BST* parent;
	struct BST* left;
	struct BST* right;
} BST;

BST* root = NULL;

BST newNode(int value);
BST BSTinsert(BST **root, int value);
BST BSTsearch(BST *x, int value);
void withinRange(BST **root, int k1, int k2);
void inOrderTreeWalkWithCheck(BST **root, BST *x, BST *y);
void inOrderTreeWalk(BST *y);
BST treeSuccessorAsAncestor(BST **root, BST *x);

int main(){
    clock_t start, end;
    int iterazione, k1, k2, i;
    double BST=0, BSTS=0, BSTW=0;
    double mediaBST;
    FILE * risultatiBST;

    srand(1);

    risultatiBST=fopen("risultatiBST.txt","w");
	if (risultatiBST==NULL)
	{
        printf ("ERRORE nell'apertura del file");
        return(1);
	}

    printf ("Inserisci k1: ");
    scanf ("%d", &k1);
    printf("Inserisci k2:");
    scanf("%d", &k2);
    printf ("BST\n");

    int inserimento, ricerca, withinrange;
    for(i = 1; i<=NUMOP; i++){
        inserimento=(70*NUMOP)/100;
        start = clock();
        for (iterazione = 1; iterazione <= inserimento; iterazione++){
            int value = rand();
            BSTinsert(&root, value);
            //end = clock();
        }

        ricerca = (15*NUMOP)/100;
        for(iterazione = 1; iterazione<=ricerca; iterazione++){
            //start = clock();
            int value = rand();
            BSTsearch(&root, value);
            //end = clock();
            //BSTS = BSTS + (double) (end-start)/CLOCKS_PER_SEC;
        }

        withinrange = (15*NUMOP)/100;
        for(iterazione = 1; iterazione <= withinrange; iterazione++){
            //start = clock();
            withinRange(&root, k1, k2);
            //BSTW = BSTW + (double) (end-start)/CLOCKS_PER_SEC;
        }
        end = clock();
        BST = BSTW + (double) (end-start)/CLOCKS_PER_SEC;

        mediaBST=BST/NUMOP;
        printf ("%d\t %f\n",i, mediaBST);
        fprintf(risultatiBST,"%d\t %f\n", i, mediaBST);
    }

    fclose(risultatiBST);

}

BST newNode(int value){
    BST *temp = (BST*)malloc(sizeof(BST));

    temp->data = value;

    temp->left = NULL;
    temp->right = NULL;
    free(temp);
    return *temp;
}

// A utility function to insert a new
// Node with given key in BST
BST BSTinsert(BST **root, int value)
{
    // Create a new Node containing
    // the new element
    BST *newnode = (BST*)malloc(sizeof(BST));
    *newnode = newNode(value);

    // Pointer to start traversing from root and
    // traverses downward path to search
    // where the new node to be inserted
    BST *x = root;

    // Pointer y maintains the trailing
    // pointer of x
    BST *y = NULL;

    while (x != NULL) {
        y = x;
        if (value < x->data)
            x = x->left;
        else
            x = x->right;
    }

    // If the root is NULL i.e the tree is empty
    // The new node is the root node
    if (y == NULL)
        y = newnode;

    // If the new key is less then the leaf node key
    // Assign the new node to be its left child
    else if (value < y->data)
        y->left = newnode;

    // else assign the new node its right child
    else
        y->right = newnode;

    // Returns the pointer where the
    // new node is inserted
    return *y;
}

BST BSTsearch(BST *x, int value){
	if ((x == NULL) || (x->data = value)){
        return *x;
	}
	if(value<x->data){
        return BSTsearch(x->left, value);
    }else{
        return BSTsearch(x->right, value);
    }
}


//withinRange
void withinRange(BST **root, int k1, int k2){
    BST *x = (BST*)malloc(sizeof(BST));
    BST *y = (BST*)malloc(sizeof(BST));
    if(k1 == k2){
        printf("%d\n", k1);
        return;
    }
    *x = BSTsearch(&root, k1);
    *y = BSTsearch(&root, k2);
    printf("%d\n", x->data);
    while(!found){
        inOrderTreeWalkWithCheck(&root, x->right, y);
        *x = treeSuccessorAsAncestor(&root, x);
        if ( x == y ){
            found = 1;
        }
        if ((x != NULL) && (!found)){
            printf("%d\n", x->data);
        }
    }
    printf("%d\n", y->data);
    found = 0;
    free(x);
    free(y);
}

void inOrderTreeWalkWithCheck(BST **root, BST *x, BST *y){
    if (x != NULL){
        if(x == y){
            inOrderTreeWalk(y);
            found = 1;
            return;
        }else{
            inOrderTreeWalkWithCheck(&root, x->left, y);
            if(!found){
                printf("%d\n", x->data);
                inOrderTreeWalkWithCheck(&root, x->right, y);
            }
        }
    }
}

void inOrderTreeWalk(BST *y){
    if(y != NULL){
        inOrderTreeWalk(y->left);
        printf("%d\n", y->data);
        inOrderTreeWalk(y->right);
    }
}

BST treeSuccessorAsAncestor(BST **root, BST *x){
    BST *y = (BST*)malloc(sizeof(BST));
    y = x->parent;
    while ((y != NULL) && (x == y->right)){
        printf("ciao");
        x = y;
        y = y->parent;
    }
    free(y);
    return *y;
}
A prima vista nella funzione newNode c'è un use-after-free: allochi un nuovo nodo nella heap, inizializzi tutto e poi deallochi la memoria, ma ritorni by value una copia della nodo che hai appena deallocato.

Direi che ci sono già qui potenziali problemi di accesso alla memoria nella costruzione dell'albero.

Ps: Sinceramente, ad un primo sguardo a qualche implementazione e alle interfacce, temo che ci siano inoltre altri leaks di memoria e problemi in genere. Purtroppo è risaputo che il linguaggio C richiede molta attenzione da questo punto di vista.
Secondo me conviene che se studi una implementazione di un binary search tree già fatta da altri (ad es. https://github.com/fbuihuu/libtree) per avere una buona base di partenza, prendendo spunti per riscriverla e estenderla per risolvere il tuo problema.

Ultima modifica di Lampo89 : 28-08-2020 alle 21:33.
Lampo89 è offline   Rispondi citando il messaggio o parte di esso
Old 30-08-2020, 17:17   #8
wingman87
Senior Member
 
Iscritto dal: Nov 2005
Messaggi: 2794
Aggiungo:
1) alla riga 144, nella funzione BSTsearch: non puoi restituire *x se x == NULL
devi prendere in considerazione il fatto che BSTsearch potrebbe non trovare il valore cercato e quindi deve poter restituire NULL. Per farlo il tipo restituito non può essere BST ma deve essere BST* (con tutte le modifiche che questo implica)

2) nella funzione treeSuccessorAsAncestor c'è lo stesso problema indicato da Lampo89 per la funzione newNode (use-after-free)
wingman87 è offline   Rispondi citando il messaggio o parte di esso
 Rispondi


realme C100x, lo smartphone economico con la batteria da 7500 mAh. La recensione realme C100x, lo smartphone economico con la bat...
Star Wars Zero Company è l'erede di XCOM 2 Star Wars Zero Company è l'erede di XCOM ...
Test ride Can-Am Origin: la moto elettrica che fa dimenticare il motore a scoppio (ma occhio all'autonomia) Test ride Can-Am Origin: la moto elettrica che f...
Logitech G325, G305 e G316 X: il tris per chi non vuole rinunciare a nulla, spendendo poco Logitech G325, G305 e G316 X: il tris per chi no...
Recensione POCO F9 pro: potenza da vero top di gamma, display da 185 Hz e finalmente una fotocamera da prendere sul serio Recensione POCO F9 pro: potenza da vero top di g...
Sky con Netflix incluso da 16,99€/mese: ...
Anthropic verso la Borsa: 42 miliardi di...
Data repatriation: cos'è e come S...
ProsperoEden: l'emulatore funzionante ch...
La sonda spaziale ESA JUICE ha effettuat...
iPhone, crash a valanga su migliaia di a...
Se mangi queste patatine puoi vincere un...
Opera browser ha una eSIM integrata da 3...
WINDTRE BUSINESS e la Protezione Civile ...
Intel prepara i chip che si illuminano? ...
HUAWEI WATCH D3 arriva in Italia: l'orol...
PS5 Pro, in Giappone si compra per estra...
Recensione Nothing Headphone (1) Pro, de...
Oltre 16 mila database Supabase leggibil...
Galaxy Z Fold8 e Fold8 Ultra ai vertici ...
Chromium
GPU-Z
OCCT
LibreOffice Portable
Opera One Portable
Opera One 106
CCleaner Portable
CCleaner Standard
Cpu-Z
Driver NVIDIA GeForce 546.65 WHQL
SmartFTP
Trillian
Google Chrome Portable
Google Chrome 120
VirtualBox
Tutti gli articoli Tutte le news Tutti i download

Strumenti

Regole
Non Puoi aprire nuove discussioni
Non Puoi rispondere ai messaggi
Non Puoi allegare file
Non Puoi modificare i tuoi messaggi

Il codice vB è On
Le Faccine sono On
Il codice [IMG] è On
Il codice HTML è Off
Vai al Forum


Tutti gli orari sono GMT +1. Ora sono le: 17:44.


Powered by vBulletin® Version 3.6.4
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.
Served by www3v