user1710702
user1710702

Reputation: 173

Trying to set a pointer of a struct to NULL in C, but getting valgrind issues

I've been trying to set a pointer to a part of a data structure in C, but valgrind is giving me an error. I recognize this error as one where I'm trying to make a non-pointer into a NULL pointer, but that's not what's happening here. What's wrong?

struct node {
    int data;
    struct node *before;
    struct node *after;
};

struct deque {
    struct node *front;
    struct node *rear;
};

int createD (Deque *d)
{
    printf ("Y\n");
    (*d) = malloc(100*sizeof(struct deque));
    (*d)->front=NULL;
    (*d)->rear=NULL;
    return 0;
}

int remD (Deque *d, char **s)
    {
    struct node *temp;
    temp=malloc(100*sizeof(struct node));
    int data;
    if (isEmptyD(d)==0)
    {
        printf ("Why?");
        return 1;
    }
    else
    {
        temp = (*d)->front;
        data = temp->data;
        (*d)->front=temp->after;
        (*d)->front->before=NULL;
        if((*d)->front==NULL)
        {
            (*d)->rear=NULL;
        }
        (*s)=malloc(100);
        (**s)=data;
        free(temp);
    }
    return 0;
}

==30983== Invalid write of size 8
==30983==    at 0x4010B5: remD (Deque.c:101)
==30983==    by 0x400C98: assign (Merge13.c:134)
==30983==    by 0x400BFB: mergesort (Merge13.c:113)
==30983==    by 0x400B03: queues (Merge13.c:64)
==30983==    by 0x400995: main (Merge13.c:26)
==30983==  Address 0x8 is not stack'd, malloc'd or (recently) free'd
==30983== 
==30983== 
==30983== Process terminating with default action of signal 11 (SIGSEGV)

(The valgrind error is in reference to the line (*d)->front->before=NULL; in remD()).

Upvotes: 0

Views: 523

Answers (2)

Jens Gustedt
Jens Gustedt

Reputation: 78903

temp->after is not set to anything useful before you use it. So temp->after->before dereferences garbage.

Initialize *temp before you use it.

Upvotes: 1

nvoigt
nvoigt

Reputation: 77294

You expect temp->after to be not NULL, because the line after (the line valgrind complains about), you assign something to the ->front of it. Are you sure it will never be NULL, but always a valid value?

Upvotes: 0

Related Questions