Error in linked list implementation

Hi ,

The code I have pasted is a linked list implentation where I am doing some create/insert/delete operations on a linked list. But I am getting the following error and unable to fix it. Any help to point out the mistake would be great.

Error: 1 error C4703: potentially uninitialized local pointer variable 'q' used


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include<stdio.h>
#include<stdlib.h>

void create(struct node **);
void insertInLinkedList(struct node **, int, int);
void display(struct node *);

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


int main()
{
	struct node *head;
	head = (struct node *)malloc(sizeof(struct node *));
	create(&head);
	insertInLinkedList(&head, 8, 1);
	display(head);
}

void create(struct node **h) {

	struct node *p;

	p = (struct node *)malloc(sizeof(struct node *));
	*h = p;
	p->data = 20;
	p->next = NULL;
	



}

void insertInLinkedList(struct node **h, int data, int position) {

	int k = 1;
	struct node *p, *q, *newNode;
	newNode = (struct node*)malloc(sizeof(struct node ));
	if (!newNode) {
		printf("Memory Error\n");
		return;
	}
	newNode->data = data;
	p = *h;

	if (position == 1) {
		newNode->next = p;
		*h = newNode;
	}
	else {
		// Traverse the list until position-1
		while ((p != NULL) && (k < position - 1)) {

			k++;
			q = p;
			p = p->next;
		}
		if (p == NULL) {   //Inserting at the end
			q->next = newNode;
			newNode->next = NULL;
		}
		else {
			q->next = newNode;
			newNode->next = p;
		}

	}


}
void display(struct node *h){

	struct node *current;
	current = h;
	while (current != NULL){
		printf("%d - > ", current->data);
		//printf("data 1 ");
		current = current->next;
	}
	printf("NULL");
	printf("\n");


}
What compiler do you use?

Line 62: q is uninitialize if line 58 is not executed.

You might initialize the local variables like so:

struct node *p = nullptr, *q = nullptr, *newNode = (struct node*)malloc(sizeof(struct node ));
Hi it microsoft visual studio 2013. See below the full error

Error 1 error C4703: potentially uninitialized local pointer variable 'q' used c:\users\simons\documents\visual studio 2013\projects\linked_list_insert_delete_nk\linked_list_insert_delete_nk\linked_list_insert_delete_nk.cpp 62 1 Linked_List_Insert_Delete_NK
Topic archived. No new replies allowed.