0

I'm trying to implement a memoryboard for the sensehat on a raspberry I got a struct that gives x and y coordinates while trying to fill them with random int i get segmentation faults.

  struct point_list *next;
  int x;
  int y;
};

struct segment_points{
  struct point_list *head;
};

struct segment_points points = {
    NULL,
};

void addNewPoint(){


    struct point_list *point_i = points.head;
    struct point_list *new_tail;
    struct point_list new_tail1;
    new_tail = &new_tail1;


    while(point_i != NULL && point_i->next != NULL){
        point_i = point_i->next;

    }


    new_tail->x = rand() % 8;

    new_tail->y = rand() % 8;


    new_tail->next = NULL;
    if(point_i != NULL){
        point_i->next = new_tail;
    }else{
        points.head = new_tail;
    }

    /*for(point_i = points.head; point_i->next; point_i->next != NULL){

            render(point_i->x,point_i->y);
    }*/

}
// for loop in main for testcase
for(int i=0; i <= 5; i++){
        printf("test\n");
        addNewPoint();
    }

i tried some printf to find out when the segmentation fault kicks in and its after the second time he goes into the whileloop

  • 1
    `new_tail` points to an object that is local to the function - the pointer becomes *dangling* after the function ends – UnholySheep Jun 17 '20 at 19:43
  • 1
    As UnholySheep mentioned, you're returning a pointer to a stack/local variable [that goes out of scope when the function returns]. To fix, remove `struct point_list new_tail1;`. And, do: `new_tail = malloc(sizeof(*new_tail));` – Craig Estey Jun 17 '20 at 19:47

0 Answers0