NeverSleepAlwaysCode
NeverSleepAlwaysCode

Reputation: 41

EXC_BAD_ACCESS with struct

The following code creates an array of structs from 1~9 as vertices, then it accepts the rest that the vertex points at. For example, if someone enters 1 as a main vertex, he would allow to enter multiple nodes for a graph. However, I'm currently facing an issue with the third while loop and the last. For this part, it should detect that the next is NULL and exit but its giving me an EXC_BAD_ACCESS error.

#include <stdio.h>
#include <stdlib.h>

struct node{
    int data;
    struct node* next;
};

int main(){
    struct node *G[10];
    for (int i = 1; i < 10; i++)
    {
        G[i]= malloc(sizeof(struct node));
        G[i]->data = i;
        G[i]->next = NULL;
        printf("%i\n", G[i]->data);
    }
    int input = 10;
    int vertixBeingModi=1;
    printf("Please enter your vertix you want to modify? \n");
    scanf("%i", &vertixBeingModi);
    while(vertixBeingModi != 0){
        while (input != 0){
            printf("Please enter the edges ? \n");
            scanf("%i", &input);
            struct node* cursor;
            struct node* newItem;
            cursor = G[vertixBeingModi];
            if (input == 0){
                break;
            }
            while(cursor->next != NULL )
            {
                cursor = cursor->next;
            }
            newItem = malloc(sizeof(struct node));
            cursor->next = newItem;
            newItem->data = input;
            cursor = G[vertixBeingModi];
        }
        printf("Please enter your vertix you want to modify? \n");
        scanf("%i", &vertixBeingModi);
        input = 1;
        if (vertixBeingModi == 0){
            break;
        }
    }
    int array[10];
    struct node* tempDegree;
    int counter = 0;
    for(int x = 1; x < 10; x++){
        tempDegree = G[x];
        if(tempDegree->next == NULL){
            continue;
        }else{
            while(tempDegree->next != NULL ){
                counter = counter + 1;
                tempDegree = tempDegree->next;
            }
            array[x] = counter;
            counter = 0;
        }
    }
    printf("%d\n", array[1]);
}

Upvotes: 1

Views: 849

Answers (1)

Jabberwocky
Jabberwocky

Reputation: 50831

You simply forgot to initialize newItem->next:

while (cursor->next != NULL)
  {
    cursor = cursor->next;
  }
  newItem = malloc(sizeof(struct node));
  newItem->next = NULL;    // <<<<<<<<<<<< add this line
  cursor->next = newItem;
  newItem->data = input;
  cursor = G[vertixBeingModi];

Upvotes: 1

Related Questions