Yíu Yíu - 10 months ago 48
C Question

Checking for invalid pointer in deque implementation

I have difficulties checking for a invalid pointer.
I have a

which I want to use as dequeue. It looks like this:

struct _dequeue_ {
struct _dequeue_* next;
struct _dequeue_* prev;
int data;
typedef struct _dequeue_ dequeue;

In my function where I want to push an element to the end of the dequeue I first check if there is already an element, and if not I want to iterate through the list until I find the element which has a null pointer in it's next pointer. However, when my loop reaches the null pointer Visual Studio stops at run time and says
hp was 0xCCCCCCCC
and that it isn't allowed to read there.

Here's the code:

void dequeue_push_back(dequeue** dq, int data)
//hp is a pointer to a struct
//dq** points to the beginning of the list
if (hp == NULL)
dequeue OnlyElement;
OnlyElement.data = data;
OnlyElement.next = NULL;
OnlyElement.prev = NULL;
hp = &OnlyElement;
dq = &hp;

while (hp)
hp = hp->next; //error occurs in this line

So my question is why this is happening and how can I successfully check for invalid pointers. Thanks in advance!

Answer Source

You reference an automatic variable (the OnlyElement).

So once the if (hp == NULL) { } block finishes, the hp pointer is not valid anymore, as the dequeue instance is destroyed.

Allocate the dequeue on a heap instead, like:

dequeue * OnlyElement = malloc(sizeof(dequeue));
OnlyElement->data = data;
OnlyElement->next = NULL;
OnlyElement->prev = NULL;
hp = OnlyElement;

The dq assignment seems wrong too.

You probably wanted this instead:

*dq = hp;

But your code is not complete, so it's just a guess.