No program output in C [closed] - c

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
#include<stdio.h>
#include<malloc.h>
typedef struct node_t {
int i;
struct node_t* link;
} node;
node* head = NULL;
int main() {
int i = 10;
node* temp = NULL;
head = (node *)malloc(sizeof(node));
temp = (node *)malloc(sizeof(node));
if(temp == NULL) {
printf("\n malloc for temp node failed! \n");
}
else {
/* linked list logic to add the elements in the beginning */
while(i<=10) {
temp->i = i;
temp->link = NULL;
if(head == NULL) {
head = temp;
}
else {
temp->link = head;
head = temp;
}
i++;
}
}
for(temp = head; temp->link != NULL; temp = temp->link) {
printf("\n The data is:%d \n",temp->i);
}
free(temp);
free(head);
return 0;
}
I'm trying a simple linked list program. I'm not getting the output.

1) You have to allocate node (tmp) each time you are assigning value to tmp. and not allocate only one time the tmp. See the following fixed code to see how to do it
2) the following for loop is wrong:
for(temp = head; temp->link != NULL; temp = temp->link) {
This for loop is fixed in the following code
3) for the free you have to browse the whole linked list and then free each node. see the following fixed code.
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct node_t{
int i;
struct node_t* link;
}node;
node* head = NULL;
int main(){
int i = 1;
node* temp = NULL;
/* linked list logic to add the elements in the beginning */
while(i<=10){
temp = (node *)malloc(sizeof(node));
if(temp == NULL){
printf("\n malloc for temp node failed! \n");
exit(1);
}
temp->i = i;
temp->link = NULL;
if(head == NULL){
head = temp;
}
else{
temp->link = head;
head = temp;
}
i++;
}
for(temp = head; temp != NULL; temp = temp->link){
printf("\n The data is:%d \n",temp->i);
}
while (head!=NULL)
{
temp = head->link;
free(head);
head = temp;
}
}

You seem to have an infinite loop! (the value of i is not changed)

You are not changing the value of variable i in the while loop as a result you never come out of the while loop.
You need something like:
int i=1;
while(i<=10){
// insert i in loop
i++;
}

You are not changing the value of loop variable i.e. i.
Also you need to do malloc inside while loop to create separate nodes. Right now, your code is modifying the same node again and again.

In addition to the node about the infinite loop, since you never modify the value of i there's something else that's wrong.
22 /* linked list logic to add the elements in the beginning */
23 while(i<=10){
24 temp->i = i;
25 temp->link = NULL;
26 if(head == NULL){
27 head = temp;
28 }
29 else{
30 temp->link = head;
31 head = temp;
Look at what you are doing in this loop. If head is NULL (it's very unlikely to be, since you allocated it back in line 15, although it's possible that the allocation could fail) you set 'head' to temp.
If head is not NULL, you set temp's 'link' to head. Then you set head to temp. Then you loop and do it all over again.
So you end up with head pointing to temp, and temp->link pointing to temp... a circular list of exactly one node.
Try this instead:
int main()
{
int i = 0;
node *temp;
/* linked list logic to add the elements in the beginning */
while(i != 10)
{
/* First, allocate a new node */
temp = (node *)malloc(sizeof(node));
if(temp == NULL)
return -1; /* yikes */
/* now set its value */
temp->i = i++;
/* and link it into the list, at the beginning */
temp->link = head;
head = temp;
}
/* Now traverse the list, starting from 'head' */
temp = head;
while(temp != NULL)
{
/* save the current node in a temporary variable */
node *temp2 = temp;
/* and move 'temp' to point to the next node in the list */
temp = temp->link;
/* print the current node */
printf("\n The data is: %d\n", temp2->i);
/* and free the memory */
free(temp2);
}
return 0;
}

Related

Why does a linked list with a double pointer cause an error?

I'm asking you a question because the assignment I was doing didn't work out.
The structure is a common link list, declaring the head pointer in the main and passing the address value of the head pointer as a parameter to the function.
The global variable top is used to determine where the current data is located.
The code currently below will detect only errors when executed.
Structure:
struct ListNode{
int data;
struct ListNode* link;
};
int top = 0;
code:
void DisplayList(ListNode** head){
if(*head == NULL){
printf("List = Empty\n");
}
else{
printf("List = ");
for(;(*head) != NULL; *head = (*head)->link){
printf("%d ",(*head)->data);
}
}
printf("\n");
}
void AddList(ListNode** head){
ListNode* temp = (ListNode*)malloc(sizeof(ListNode));
int num;
printf("Data register) ");
scanf("%d",&num);
temp->data = num;
temp->link = NULL;
top++;
if(*head == NULL){
*head = temp;
}
else{
for(;(*head)->link != NULL; *head = (*head)->link){}
(*head)->link = temp;
}
DisplayList(head);
}
the expected result:
Data register) 10
List = 10
Data register) 20
List = 10 20
Data register) 30
List = 10 20 30
You shouldn't modify *head in the loops. You need to use a local variable to step through the list, otherwise you're changing the caller's variable to point to the end of the list.
void DisplayList(ListNode** head){
if(*head == NULL){
printf("List = Empty\n");
}
else{
printf("List = ");
for(ListNode *step = *head;step != NULL; step = step->link){
printf("%d ",step->data);
}
}
printf("\n");
}
void AddList(ListNode** head){
ListNode* temp = (ListNode*)malloc(sizeof(ListNode));
int num;
printf("Data register) ");
scanf("%d",&num);
temp->data = num;
temp->link = NULL;
top++;
if(*head == NULL){
*head = temp;
}
else{
ListNode *step = *head;
for(;step->link != NULL; step = step->link){}
step->link = temp;
}
DisplayList(head);
}
Your error is in how you traverse the list:
for(; (*head)->link != NULL; *head = (*head)->link) {}
At the beginning, *head is the head of the list from the calling function. By assigning to it, you overwrite it continuously, until it becomes null.
Instead, you should assign to head: It holds the address of the head node in the calling function at first and the address of the link pointer of the previous node in subsequent iterations:
for(; (*head)->link != NULL; head = &(*head)->link) {}
After this loop, head holds the address of the pointer where the new node should be stored. Assign the new node to that pointer directly:
*head = temp;
This will update the head pointer of the calling function when the list was empty and the link member of the previous node otherwise. You don't have to treat the case where the list is empty specially.
The insertion function might now look like this:
void AddList(ListNode** head, int num)
{
ListNode* temp = malloc(sizeof(ListNode));
temp->data = num;
temp->link = NULL;
while (*head) head = &(*head)->link);
*head = temp;
}
(In my opinion, reading the input and printing the list shoudl not be part of te insertion function.)
Regarding your printing function: Seeing a function like that:
void DisplayList(ListNode** head)
raises a red flag: Passing a pointer to node pointer signals that you want to modify the list (and you inadvertently do that), but printing the list only inspects it. Change the signature to
void DisplayList(const ListNode* head)
then use head instead of (*head) in the function. (Rule of thumb: If you never use *head = ... somewhere in the list, you don't need a pointer to node pointer.)

try to find middel but program crash linked list in c with two pointers

i write function whom Traverse linked list using two pointers. Move one pointer by one and other pointer by two. When the fast pointer reaches end slow pointer will reach middle of the linked list.
but my code crash when i try to move temp pointer by two
#include <stdio.h>
#include <stdlib.h>
#define MEM (struct node*) malloc(sizeof(struct node))
void addl(); //add elements at last
void print(); //print linked list
void addf(); //add element at first
void addm(); //add element at middel
struct node {
int data;
struct node* next;
};
struct node* head;
void addl()
{
struct node* new, *temp;
temp = head;
new = MEM;
printf("\n\t\tenter any number : ");
scanf("%d", &new->data);
new->next = 0;
if (temp == 0)
head = new;
else {
while ((temp->next != 0))
temp = temp->next;
temp->next = new;
}
}
void print()
{
struct node* temp = head; //
printf(" \n Elements are : ");
while (temp != 0) {
printf(" %d ", temp->data);
temp = temp->next;
}
}
void addf()
{
struct node* new;
new = MEM;
printf("\n\t\tenter any number : ");
scanf("%d", &new->data);
new->next = head;
head = new;
}
void addm()
{
struct node* new, *temp, *med;
temp = head;
med = head;
new = MEM; //MEM #define for dynamic memory allocation
printf("\n\t\tenter m any number : ");
scanf("%d", &new->data);
if (temp == 0)
head = new;
else {
while ((temp = temp->next != 0)) {
med = med->next;
temp = temp->next; //fist move
temp = temp->next; //2nd move when i add program crash
}
// new->next=med;
//med->next=new;
printf("\n\t\tDATA : %d\n", med->data);
}
}
int main()
{
head = 0;
int i = 5; //create linked list
while (i) {
system("cls");
addf();
addl();
i--;
}
addm();
print();
return 0;
}
as of now addm not add anything in linked list because code crash while i try to found mid of linked list
The crash is due to these two line -
temp=temp->next;//for one move
temp=temp->next;//for second move when i add this program crash
Let's think of two situations -
1) List has one element. Then after the while check condition, dur to temp=temp->next line temp will point to NULL. In next temp=temp->next line you are trying to de-reference that NULL. That will crash
2) List have 2 elements. After while condition check temp will point to last element. And after next temp=temp->next line temp will point to NULL. Now in very next line you are trying to de-reference that NULL. Which is another point of crash
You need to remove one temp=temp->next from inside loop as it advances temp by 3 position in each loop iteration which is clearly a logical bug. Node that after that removing one of them will not eliminate the chance of crash.
Another thing is that the commented code is also wrong.
// new->next=med;
//med->next=new;
You may have wanted to do -
new->next = med->next;
med->next = new;

Why I can't traverse this linked list in C?

I'm having a hard time to understand why I'm having an infinite loop while I try to traverse a linked list I made to practice :
#include <stdio.h>
#include <stdlib.h>
typedef struct noeud {
int val;
struct noeud *next;
} noeud;
noeud* add_first(noeud* head, int val){
noeud* p = malloc(sizeof(noeud));
if(p == NULL){
puts("ERROR ALLOCATING NODE ");
exit(-1);
}
else{
p->val = val;
p->next = head;
}
return p;
}
void discover(noeud* head){
noeud* current = head;
while(current != NULL){
printf("---|%d|-|%p|---",current->val, current->next);
current = head->next;
}
}
int main(){
noeud* head = malloc(sizeof(noeud));
head->next = NULL;
head = add_first(head, 5);
head = add_first(head, 4);
head = add_first(head, 3);
head = add_first(head, 8);
discover(head);
return 0;
}
Here's what I did : I created a function like push to add nodes at first, each one will link to the previous one, I'm updating head to take the first node each time I push something new .
Then I'm just trying to print the result and the adresse of the next node, to do so, I used a while loop and I would verify for the NULL condition, I believe the problem is that after updating head, then head->next is not NULL anymore, but I can't really find a way to keep the last element point to null .
In the beginning of your function, you copied the head pointer to a stack variable, noeud* current = head;, but then inside the while loop you assign the stack variable to the next member of head, current = head->next;.
This will just lead to continuous assignment to the same next address and never moves current just switch it to this:
current = current->next;
It looks strange how you allocate memory for a "head node", you don't need to do that. All you need is a single HEAD pointer like so noeud* head = NULL;.
Your main() becomes:
int main(){
noeud* head = NULL;
head = add_first(head, 5);
head = add_first(head, 4);
head = add_first(head, 3);
head = add_first(head, 8);
discover(head);
return 0;
}
Then you have to modify your printing function as per the Josh Weinstein answer:
void discover(noeud* head){
noeud* current = head;
while(current != NULL){
printf("---|%d|-|%p|---\n",current->val, current->next);
current = current->next;
}
}

C: Linked list bad access of memory

I have to work on linked lists and get a bad access error even before something happens in my main. I don't know what's wrong. I am relatively new to dynamic memory management. It would be nice if someone could take a look on the functions. The declaration was given by the professor, so we have to return a DoubleNote*.
My code is below:
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
double var;
struct node *next;
} DoubleNode;
DoubleNode* insertFirst(DoubleNode* head, double d){
DoubleNode* new_head;
new_head = (DoubleNode*)malloc(sizeof(DoubleNode));
if (new_head == NULL) {
printf("Error: Allocating memory for new node failed!");
exit(1);
}
new_head->var = d;
new_head->next = head;
head = new_head;
return head;
}
DoubleNode* inserLast(DoubleNode* head, double d){
DoubleNode* current = head;
while (current != NULL) {
current = current->next;
}
current->next = (DoubleNode*)malloc(sizeof(DoubleNode));
if (current->next == NULL) {
printf("Error: Allocating memory for new node failed!");
exit(1);
}
current->next->var = d;
current->next->next = NULL;
return head;
}
DoubleNode* inverseDoubleListCon(DoubleNode* head){
DoubleNode* current = head; // iteration variable starts on head of old list
DoubleNode* conHead = current; // Head of the new list
while (current != NULL) {
current = current->next; //iteration step
DoubleNode* newConHead = (DoubleNode*)malloc(sizeof(DoubleNode)); //allocating memory for new head
if (newConHead == NULL) {
printf("Error: Allocating memory for new node failed!");
exit(1);
}
newConHead = current; // new_head is the next variable in the old list
newConHead->next = conHead; //new head points to old head of the new list
conHead = newConHead; // new head is set
}
return conHead;
}
void printList(DoubleNode* head){
DoubleNode* current = head;
while (current != NULL) {
printf("%lf\n", current->var);
current = current->next;
}
}
int main(){
DoubleNode* head = NULL;
DoubleNode* inverseHead = NULL;
double d;
int i;
int sizeOfList;
printf("Insert amount of variables: \n");
scanf("%d", &sizeOfList);
for (i = 0; i < sizeOfList; i++) {
printf("Insert variable for node [%d]: \n", i);
scanf("%lf", &d);
head = insertFirst(head, d);
}
printList(head);
inverseHead = inverseDoubleListCon(head);
printList(inverseHead);
return 0;
}
Firstly sizeOfList is not initalised. You need to add code to get the value of the size from the user.
You are also not updating the value of the head pointer from the insertFirst function. The code below should help.
DoubleNode* head= NULL;
// Code to get the value of sizeofList
for (i = 0; i < sizeOfList; i++)
{
...
head = insertFirst(head, d);
}
The reverse function is overly complicated. You are allocating memory in newConHead which is not required for reversing a linked list.
I would suggest a rewrite along the lines of How to reverse a singly linked list using only two pointers? or http://www.geeksforgeeks.org/write-a-function-to-reverse-the-nodes-of-a-linked-list/

Linked list shows only first node element on printing

I am trying to create a linked list in order to enhance my concepts of pointers and address. I have to create linked list in following way:
(1) Read all the nodes together at once at terminal.
(2) Then show the final linked list so formed at last.
How i try to do so ?
I am reading first the size of linked list (total number of nodes to be entered). Then i read all the nodes 1 by one in do-while loop. After reading all the nodes i try to create linked list. I differentiate the case when the node is first node to be created by a count variable which will have count=0 when the node is first node after that it will be in another loop.
The output i get is as follows:
enter the size of node
4
start entering the number of elements until your size
2
3
4
5
Printing linked list
2-> //It don't print the other nodes, Just first one
hp#ubuntu:~/Desktop/pointer$
My full code to do so is :
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
struct node
{
int freq;
struct node * next;
};
typedef struct node node;
node * tree;
void main()
{
int size, data;
int count = 0; //this count flag is to check is it's first node or not inside the do-while loop.
tree = NULL;
printf("enter the size of node\n");
scanf("%d", & size);
printf("start entering the number of elements until your size\n");
node * temp3 = tree;
node * prev;
//Problem creating area is below
do
{
scanf("%d", & data);
if (count == 0)
{
node * temp;
temp = (node * ) malloc(sizeof(node));
temp-> freq = data;
temp-> next = NULL;
prev = temp;
}
else if (count != 0)
{
node * temp;
temp = (node * ) malloc(sizeof(node));
temp-> freq = data;
temp-> next = NULL;
prev-> next = temp;
}
size--;
++count;
}
while (size > 0);
printf("Printing linked list\n");
node * temp1;
temp1 = prev;
//there may be problem here
while (temp1-> next != NULL)
{
printf("%d-> ", temp1-> freq);
temp1 = temp1-> next;
}
printf("\n");
}
Couldanyone please help me in printing the full linked list by pointing me the error with it's solution ?
Okay there is some unnecessary pointers and a few pointer mistakes being made, for ease of answering I've rewritten your code, I'll try to explain what I did here:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
struct node
{
int freq;
struct node * next;
};
typedef struct node node;
//only need two pointers when building a linked list, one for the top and one for the
//current node
node *tree = NULL, *curr = NULL; //init both pointers to NULL initially
int main()
{
int size, data; //dont need count, you'll see in a minute why
printf("enter the size of node\n");
scanf("%d", & size);
printf("start entering the number of elements until your size\n");
//Problem creating area is below
do
{
scanf("%d", &data);
if (tree == NULL) //just test for top node being NULL instead of using count
{
node *temp;
temp = malloc(sizeof(node));
temp->freq = data;
temp->next = NULL;
//stylistically i like using curr rather than prev, just a style choice
tree = temp; //set tree to first node
curr = tree; //make the top node the current node
}
else //don't need else if, there are only two conditions
{
node *temp = malloc(sizeof(node));
temp->freq = data;
temp->next = NULL;
curr->next = temp; //set the next node in list to the new one
curr = curr->next; //here's where you had pointer issues, move the current
//to the newly created node
}
size--;
}
while (size > 0);
printf("Printing linked list\n");
curr = tree; //reuse curr, no need to make a new pointer
//test for the current node being NULL, takes care of special case of empty list
//causing a segfault when you attempt to access a member of an invalid pointer
while (curr != NULL)
{
printf("%d->", curr->freq);
curr = curr->next; //move to next item in list
}
printf("\n");
return 0;
}
I ran a sample run with size of 3 and inputs of 1, 2, and 3, and I get as output: 1->2->3->
You got two problems.
else if (count != 0)
{
node * temp = prev;
temp = (node * ) malloc(sizeof(node));
temp-> freq = data;
temp-> next = NULL;
prev-> next = temp;
}
You aren't changing prev to point to your new node. It still points to '2' in your scenario, and you'll never have more than two nodes in the list.
Try something like
else if (count != 0)
{
/* node * temp = prev; */ //This code is not doing anything useful
temp = (node * ) malloc(sizeof(node));
temp-> freq = data;
temp-> next = NULL;
prev-> next = temp;
prev = temp;
}
Next, your printing loop should probably be
node* temp1 = start; //You need a variable that points to the first node in the list
do
{
printf("%d-> ", temp1-> freq);
temp1 = temp1-> next;
}
//The last item will always have next == NULL, and must be included
while (temp1-> next != NULL);

Resources