Conditional jump or move depends on uninitialised value(s) in LinkedList - initialization

I keep getting the Conditional jump or move depends on uninitialised value(s) in Valgrind for the function printList() and freeList(). I read a few posts and the problem was because head was not initialized after malloc() so I added newList->head = NULL after malloc in my createList() function. I am not sure how to fix this error. Any help is really appreciated! I am really new to C so I really don't know what the problem is...
typedef struct node{
int year;
int win;
struct node* next;
}node_t;
typedef struct slist{
node_t* head;
int size;
}slist_t;
node_t* makeNode(int year, int win){
node_t* newNode = (node_t*) malloc(sizeof(node_t));
if (newNode == NULL){
return NULL;
}
newNode->year = year;
newNode->win = win;
return newNode;
}
void freeNode(node_t* node){
if (node == NULL){
return;
}
free(node);
}
slist_t* createList(){
slist_t* newList = (slist_t*) malloc(sizeof(slist_t));
if (newList == NULL){
return;
}
newList->head = (node_t*) malloc(sizeof(node_t));
newList->head = NULL;
newList->size = 0;
return newList;
}
node_t* addFirst(slist_t* list, int year, int win){
node_t* node = makeNode(year, win);
if (list == NULL){
return;
}
if (node == NULL){
return;
}
if (list->head == NULL){
list->head = node;
}
else{
node->next = list->head;
list->head = node;
}
list->size += 1;
return node;
}
void printList(slist_t* list){
if (list == NULL){
return;
}
node_t* itr = list->head;
while(itr != NULL){
printf("%d, %d wins\n", itr->year, itr->win);
itr = itr->next;
}
printf("\n");
}
void freeList(slist_t* list){
node_t* node = list->head;
while (node){
node_t* temp = node;
node = node->next;
free(temp);
}
free(list);
}
int main(){
slist_t* list = createList();
addFirst(list, 2014, 71);
addFirst(list, 2015, 78);
addFirst(list, 2016, 93);
addFirst(list, 2017, 93);
addFirst(list, 2018, 108);
printList(list);
freeList(list);
return 0;
}

The problem is that makeNode does not initialise newNode->next. If it happens to have the value 0 (NULL), things will go fine, but try to add this statement in makeNode and then run the program:
newNode->next = 1000000;
Now it is more likely you get a segmentation fault or some other weird behaviour. So add this line instead:
newNode->next = NULL;
Not your issue, but this sequence of assignments produces a memory leak:
newList->head = (node_t*) malloc(sizeof(node_t));
newList->head = NULL;
After having allocated memory, you immediately lose the reference to it, by overwriting that reference with NULL. You should just drop the first of these two assignments. The first node is created later, when you call addFirst, so no node should be allocated here.

Related

When finding cycles in undirected graphs, why can't we just keep track of previous parent node while using BFS traversal

Basically when we use DFS we just check if the adjacent nodes for a newly visited node have been already visited and they are not the parent node which made the DFS call for this node. If this is the case cycle is present.
I was using similar thing for BFS while keeping track of previous parent node and my logic doesn't seem to work. The test case on which my code is failing is too big to understand the problem. Can anyone let me know where my logic is broken? Thank you in advance
bool bfs(vector<int> adj[], bool isVisited[], int s, int V)
{
queue<int> q;
q.push(s);
isVisited[s] = true;
int parent = s;
int prevParent = -1;
while(q.empty() == false)
{
int u = q.front();
prevParent = parent;
parent = u;
q.pop();
for(int i = 0 ; i < adj[u].size() ; i++)
{
if(isVisited[adj[u][i]] == false)
{
isVisited[adj[u][i]] = true;
q.push(adj[u][i]);
// parent[][i]] = u;
}
else
{
if(adj[u][i] != prevParent)
return true;
}
}
}
return false;
}
bool isCycle(int V, vector<int> adj[]) {
// Code here
bool isVisited[V] = {false};
for(int i = 0 ; i < V ; i++)
{
if(isVisited[i] == false)
if(bfs(adj, isVisited, i, V) == true)
{
return true;
}
}
return false;
}

code got strucked in a infinite loop when I tried to reverse a linked list using recursion

I was trying to reverse a linked list using recursion but when I tried to print out all the elements of the linked list at first it was printing out elements as expected but after printing out the last element it started printing the last and second last element repeatedly. I tried to debug it and I think the problem is that the last element is pointing towards the second last element whether it should be pointing towards NULL. I am not able to figure out what is wrong with my code so please help me out.
example- input 1,2,3,4,5,6
expected output 6,5,4,3,2,1
actual output 6,5,4,3,2,1,2,1,2 ...
#include<iostream>
using namespace std;
class node{
public:
int val;
node *next;
node(int val)
{
this->val = val;
this->next = NULL;
}
node(int val,node *next)
{
this->val= val;
this->next=next;
}
};
void insertAtTail(node *&head,int val){
node *n = new node(val);
if (head==NULL)
{
head = n;
return;
}
node *temp = head;
while (temp->next!=NULL)
{
temp = temp->next;
}
temp->next=n;
}
void display(node *head)
{
node *n = head;
while (n!=NULL)
{
cout << n->val << "->";
n = n->next;
}
cout << "NULL" << endl;
}
node* reverseRecursive(node *&head)
{
if (head == NULL || head->next==NULL)
{
return head;
}
node *nHead = reverseRecursive(head->next);
head->next->next = head;
head->next == NULL;
return nHead; // 1->2->3->4->5->6->NULL
}
int main()
{
node *head = NULL;
insertAtTail(head,1);
insertAtTail(head,2);
insertAtTail(head,3);
insertAtTail(head,4);
insertAtTail(head,5);
insertAtTail(head,6);
display(head);
node *newhead = reverseRecursive(head);
display(newhead);
return 0;
}
There is a bug in function reverseRecursive().
Line head->next == NULL; should be head->next = NULL;
node* reverseRecursive(node *&head)
{
if (head == NULL || head->next==NULL)
{
return head;
}
node *nHead = reverseRecursive(head->next);
head->next->next = head;
head->next == NULL; // <<< should be head->next = NULL;
return nHead; // 1->2->3->4->5->6->NULL
}
Not sure which compiler you were using, but this statement will typically generate a warning.

Tree returning the maximum value

50
/ \
30 70 (( which should return 50+70=120 ))
int MyFunction(struct node *root){
struct node *ptr=root;
int leftsum=0;
int rightsum=0;
if(ptr==NULL){
return;
}
else{
MyFunction(ptr->left);
leftsum=leftsum+ptr->key;
MyFunctipn(ptr->right);
rightsum=rightsum+ptr->key;
return (root->key+max(leftsum,rightsum));
}
}
for that, I've written this code. Maybe it is wrong so please help me as I'm new in this field. I want to write a recursive code such a way that it compares two leaf node(left and right) and returns the maximum to the parent nood.
The recursive function should look something like this:
int getMaxPath(Node* root){
// base case, We traveled beyond a leaf
if(root == NULL){
// 0 doesn't contribute anything to our answer
return 0;
}
// get the max current nodes left and right children
int lsum = getMaxPath(root->left);
int rsum = getMaxPath(root->right);
// return sum of current node value and the maximum from two paths starting with its two child nodes
return root->value + std::max(lsum,rsum);
}
Full code:
#include <iostream>
struct Node{
int value;
Node* left;
Node* right;
Node(int val){
value = val;
left = NULL;
right = NULL;
}
};
// make a tree and return a pointer to it's root
Node* buildTree1(){
/* Build tree like this:
50
/ \
30 70
*/
Node* root= new Node(50);
root->left = new Node(30);
root->right = new Node(70);
}
int getMaxPath(Node* root){
if(root == NULL){
// 0 doesn't contribute anything to our answer
return 0;
}
int lsum = getMaxPath(root->left);
int rsum = getMaxPath(root->right);
return root->value + std::max(lsum,rsum);
}
int main() {
using namespace std;
Node* root = buildTree1();
int ans = getMaxPath(root);
cout<< ans <<endl;
return 0;
}
int Sum(struct node *root)
{
if(root->left == NULL && root->right== NULL)
return root->key;
int lvalue,rvalue;
lvalue=Sum(root->left);
rvalue=Sum(root->right);
return root->key+max(lvalue,rvalue);
}
int max(int r,int j)
{
if(r>j)
return r;
else
return j;
}

Deleting data from a linked list using pointers

I was trying to come up with a program that will use a linked list to read data off a file and delete grades that are under 50%. I came up with this code but it gives me the error "type float' argument given todelete', expected pointer". Please help if you can.
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<string.h>
struct node
{
int id;
char name[10];
float grade;
struct node * next;
};
void build_link(struct node * ap);
void happy (struct node * bp);
void delete_fail (struct node *np);
int main(int argc, char *argv[])
{
struct node head;
head.next = NULL;
build_link( &head);
happy(head.next);
delete_fail (head.next);
system("PAUSE");
return 0;
}
void build_link(struct node * tmp)
{
int nu_id;
char nu_nam[10];
float nu_grade;
struct node * np;
FILE *fp;
fp = fopen("Student.txt","r");
while (fscanf( fp,"%d %s %f", &nu_id, nu_nam, &nu_grade ) != EOF)
{
np = (struct node *) malloc ( sizeof (struct node) );
strcpy (np->name,nu_nam);
np->id = nu_id;
np->grade = nu_grade;
np->next = NULL;
tmp->next = np;
tmp = tmp->next;
}
}
void happy(struct node *np)
{
while (np != NULL)
{
printf(" %d %s %f \n", np->id, np->name, np->grade);
np = np->next;
}
}
void delete_fail(struct node* grade)
{
node *np;
if(np == NULL)
printf("\nElement not found");
else
{
This is where my problem lies. I am not sure how to fix this part right here.
if( np->grade <50 )
np->grade = delete(np->grade);**
else
if(np->grade > 60)
np->grade = np->grade;
}
}

Infinite loop : Process not terminating properly

struct node
{
int data;
node* left;
node* right;
};
int secondlargest(struct node* a)
{
while(a->right != NULL){
secondlargest(a->right);
}
return a->data;
}
I am not able to trace where have I done the mistake and why its not coming out of the while loop.
Your mistake is that you shouldn't use an while but instead an if because it is recursive, but what do you want the function to return? the data of the last member? if so it should be like this:
int secondlargest(struct node* a) {
if(a == NULL) return -1;
secondlargestr(a);
}
int secondlargestr(struct node* a) {
if(a->right!=NULL) return secondlargest(a->right);
return (a->data);
}
If you insist on the recursive version, change the while to if.
int secondlargest(node* a)
{
if(a == null){
// if the first node is already NULL
return -1;
}
if(a->right == NULL){
return a->data;
}else{
return secondlargest(a->right);
}
}
Basics of recursion:
Must have base case
Break down problem size recursively
If you want the iterative way:
int secondlargest(node* a)
{
node* temp = a;
int data = -1;
while(temp != null){
data = temp->data;
temp = temp->right;
}
return data;
}

Resources