Torna indietro   Hardware Upgrade Forum > Software > Programmazione

Recensione Zenfone 11 Ultra: il flagship ASUS ritorna a essere un 'padellone'
Recensione Zenfone 11 Ultra: il flagship ASUS ritorna a essere un 'padellone'
Zenfone 11 Ultra ha tantissime qualità interessanti, fra cui potenza da vendere, un display di primissimo livello, un comparto audio potente e prestazioni di connettività fra le migliori della categoria. Manca però dell'esclusività del predecessore, che in un settore composto da "padelloni" si distingueva per le sue dimensioni compatte. Abbiamo provato il nuovo flagship ASUS, e in questa recensione vi raccontiamo com'è andata.
Appian: non solo low code. La missione è l’ottimizzazione dei processi con l'IA
Appian: non solo low code. La missione è l’ottimizzazione dei processi con l'IA
Abbiamo partecipato ad Appian World 2024, evento dedicato a partner e clienti che si è svolto recentemente nei pressi di Washington DC, vicino alla sede storica dell’azienda. Nel festeggiare il 25mo anniversario, Appian ha annunciato diverse novità in ambito intelligenza artificiale
Lenovo ThinkVision 3D 27, la steroscopia senza occhialini
Lenovo ThinkVision 3D 27, la steroscopia senza occhialini
Primo contatto con il monitor Lenovo ThinkVision 3D 27 che grazie a particolari accorgimenti tecnici riesce a ricreare l'illusione della spazialità tridimensionale senza che sia necessario utilizzare occhialini
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: 2745
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: 2993
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: 2745
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: 2745
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


Recensione Zenfone 11 Ultra: il flagship ASUS ritorna a essere un 'padellone' Recensione Zenfone 11 Ultra: il flagship ASUS ri...
Appian: non solo low code. La missione è l’ottimizzazione dei processi con l'IA Appian: non solo low code. La missione è ...
Lenovo ThinkVision 3D 27, la steroscopia senza occhialini Lenovo ThinkVision 3D 27, la steroscopia senza o...
La Formula E può correre su un tracciato vero? Reportage da Misano con Jaguar TCS Racing La Formula E può correre su un tracciato ...
Lenovo LEGION e LOQ: due notebook diversi, stessa anima gaming Lenovo LEGION e LOQ: due notebook diversi, stess...
La Cina ha lanciato la missione Shenzhou...
La sonda spaziale NASA Psyche comunica v...
Dacia Duster, prima guida: con le versio...
Google Pixel 8 Pro 256 GB a 928€ (minimo...
Arriva l'ok da Parlamento europeo sul di...
RISC-V: l'uso dell'ISA open-source da pa...
Amazon scatenata: iPad a 399€, airfryer ...
SK hynix, costruzione della Fab M15X ai ...
Oggi 459€ per utenti Prime il portatile ...
Sta per succedere! La prima gara a guida...
Parthenope: un nuovo RPG investigativo t...
Urbanista Malibu: ecco come va la cassa ...
Gas Station Simulator è costato 1...
AOC Graphic Pro U3, tre nuovi monitor pe...
Wacom Movink: per la prima volta il disp...
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: 05:45.


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