Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

malloc() causing EXC_BAD_ACCESS error in Xcode

Tags:

c

xcode

malloc

I am trying to implement the Linked List data structure for my college course, but on executing the code the following line produces an EXC_BAD_ACCESS(code=1, address=0x8) error.

temp->next = (ptrtonode) malloc(sizeof(struct node));

Following is the code in its entirety.

#include <stdio.h>
#include <stdlib.h>
typedef struct node *ptrtonode;
typedef ptrtonode header;

struct node
{
    int data;
    ptrtonode next;
};

ptrtonode create(int n)
{
    int i;
    header temphead = NULL;
    ptrtonode temp = temphead;
    for(i=0;i<n;i++)
    {
        temp->next = (ptrtonode) malloc(sizeof(struct node));
        printf("Enter data for node %d: ", i+1);
        scanf("%d", &temp->next->data);
        temp = temp->next;
    }
    temp->next = NULL;
    return temphead;
}

int main(int argc, const char * argv[])
{
    header head;
    int n;
    printf("How many nodes do you wish to create?");
    scanf("%d", &n);
    head = create(n);
}

Any help would be appreciated. Thanks all!

like image 627
vigneshwerv Avatar asked Nov 28 '25 22:11

vigneshwerv


1 Answers

On first iteration of the for loop inside the create() function temp is NULL, which is then dereferenced causing the failure (not malloc() causing the failure). You will need to restructure the code slightly to prevent dereferencing a NULL pointer.

Other points:

  • casting the return value of malloc() is not required.
  • check the result of scanf() to ensure n was assigned a valid integer (and confirm that the int is positive):

    /* scanf() returns the number of assignments made,
       which in this case should be 1. */
    if (1 == scanf("%d", &n) && n > 0)
    {
        /* 'n' assigned a sensible value. */
    }
    
like image 166
hmjd Avatar answered Nov 30 '25 10:11

hmjd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!