I got stuck when trying to remove even number from queue in C programming. Here is the code:
My data structure for Queue:
typedef struct _listnode
{
int data;
struct _listnode *next;
} ListNode; // You should not change the definition of ListNode
typedef struct _linkedlist
{
int size;
ListNode *first;
} LinkedList; // You should not change the definition of LinkedList
typedef struct _queue
{
LinkedList list;
} Queue;
And I am calling from my main:
case 3:
deleteEven(&q); // You need to code this function
printf("Result:\n");
printList(&q.list);
break;
What I am trying to do is first, I tried to check if the queue is empty. Then I will get the linked list head and modulus with 2, if getting 0 means it's even number and then I will dequeue it from the queue.
However, with these code, when I try to dequeue even numbers from queue, it just stopped working and not showing any error message.
Anybody know how to solve this? Thanks in advance.
In your function deleteEven's while loop you do this -
free(odd->list.first->data); //problem 1
odd->list.first->data= odd->list.first->next; //problem 2- assigning pointer type to int
Problem 1- But you haven't allocated memory to odd->list.first->data , it is an integer variable. And if you try to free such thing can cause error in your program (you should not free memory not allocated by malloc or similar functions)
You allocate memory to odd , so free pointer odd.
Even you should not free inside your while loop, as you allocate memory only one time .
Problem 2 - You assign pointer type to int. That's may also be one of reason for this error .
You should write loop like this -
while (!isEmptyQueue(odd)) {
enqueue(que, odd->list.first->data);
odd->list.first= odd->list.first->next; // increment pointer
}
free(odd);
3. While calling function dequeue -
dequeue(que->list.first->data);
int is passed but it expects Queue * .
Its type is int but you return NULL from it (return -1 or something to show failure).
Related
typedef struct node {
int data;
struct node *next;
} Node;
void checkEmpty(Node *list) {
printf(list == NULL ? "true" : "false");
}
The first time, I created the main() function, made a list directly in it, and called checkEmpty(). It printed true.
int main() {
Node *list;
checkEmpty(list); // it return true
return 0;
}
Then, I created a new function menu(), created a list inside it, and called checkEmpty(). It printed false.
void menu() {
Node *list;
checkEmpty(list);
}
int main() {
menu(); // it return false
return 0;
}
Why does this happen?
The declaration Node *list inside a function does not initialize list. Its value is indeterminate, meaning it does not have to behave as if it has any fixed value at all. The compiler may generate code that uses a different value for it each time it is used, such as reading from memory on one occasion or using a value from a processor register on another.
To fix your program, give list an initial value with Node *list = 0; or Node *list = NULL.
Also turn on compiler warnings and elevate warnings to errors. Check your compiler documentation for the switches to do that. Also pay attention to compiler warning and error messages.
You have a pointer of type Node that is currently not pointing to any memory specifically. However, there can already be junk data stored into the memory block of the pointer so that technically it's not pointing to NULL and it is pointing to something. The first time you created a pointer, could've been by chance that it's already NULL in the memory block.
So,if you do declare the pointer, it is always good practice to have the pointer point to NULL first.
Node *list = NULL;
I am getting a segmentation fault whenever I try to print the value stored within a struct. Using Valgrind, I was able to narrow it down a bit to one block of code, but I am unsure what I am doing wrong. Am I initializing my struct incorrectly?
Whenever I run valgrind, it tells me that there is an invalid write of size 8 where I say newList->data = d.
typedef struct List {
struct List *np[Ends]; // next/prev neighbors
Data data;
} *List;
typedef void *Data;
static void put(Data d) {
List newList = malloc(sizeof(List));
newList->data = d;
}
This is an example of why it's bad practice to typedef a pointer.
Because List is defined as an alias for struct List *, sizeof(List) gives you the size of a pointer, not the size of the struct. As a result, you're not allocating enough memory.
You instead want either malloc(sizeof(struct List)) or (preferably) malloc(sizeof *newlist)
I am new to programming and have just learned C shortly. Now my problem is, i tried to malloc a struct array, and then use it to fill in some information. but keep getting the heap overflow error report.
here is my declaration of struct in the h.file.
typedef struct llnode {
char llnodename[256];
int ll_index;
struct llnode* next;
} llnode;
//the struct of a linked list.
typedef struct node_stru {
char nodename[256];
int node_index;
} node_stru;
//the struct of the node.
and the pointer:
node_stru *node_list = (struct node_stru*)malloc(n_nodenumber*(sizeof(node_stru)));
but later when i wants to use the linked list to fill in some information,it give me the heap overflow.
llnode* ptr=Ahead;
while (ptr!=NULL){
printf("the name%s, the index%d", ptr->llnodename, ptr->ll_index);
strcpy(node_list[n_index].nodename, ptr->llnodename);
node_list[n_index].node_index = ptr->ll_index;
n_index++;
ptr = ptr->next;
}
The error report: I do malloc a 4*(256+4) memory, but it still not working.
0x619000000490 is located 0 bytes to the right of 1040-byte region [0x619000000080,0x619000000490)
You've allocated a fixed size for node_list, but there's nothing stopping your loop from walking off the end. For example, if n_nodenumber is 4 you can store 4 nodes. But if Ahead is linked to 5 nodes it will walk off node_list. That's assuming n_index starts at 0.
At minimum your loop should assert(n_index < n_nodenumber) to provide a better error when the loop walks off the array. That's all I can say without seeing a complete example.
I created a program that uses pointers and nodes for a linked list. I narrowed down the problem to the following lines of code. Every time my program reaches the printf section it crashes.
typedef struct book {
char title[50];
char author[50];
}BOOK;
typedef struct Node {
struct Node* next;
BOOK info;
int priority;
}node;
I narrowed down the problem to the following lines of code. Every time my program reaches the printf section it crashes.
void peek(node **head) {
node *temp = *head;
printf("%s by %s has been peeked.",temp -> info.title , temp -> info.author);
}
Any help is greatly appreciated!
EDIT :
in my main i have:
BOOK bookDetails() {
BOOK b;
printf("\nEnter book title: ");
fflush(stdout);
scanf("%s", b.title);
printf("\nEnter the author: ");
fflush(stdout);
scanf("%s",b.author);
return b;
}
..and in the main(void):
node *queue = NULL;
case 4: peek(&queue);
break;
In other cases i added information into &queue using BOOK b to link to struct book
bookDetails()
your BOOK b; goes out of scope at the end of bookDetails();
you would be wise to ether:
pass a pointer to a BOOK struct into bookDetails
you would need to change your return type to int and use it for error checking.
dynamically allocate some heap memory inside bookDetails() with malloc() for that
book struct.
requires #include and free() when you are done with the memory.
main(void)
what this line does node *queue = NULL;
in English:
allocate a new pointer on the stack to a node struct then, set the pointer to NULL.
when you pass this to peek naturally you will get some errors because you cannot deference a NULL pointer.
struct Node and queue
you have the beginnings of a linked list structure with Node but, then I see you using this pointer to pointers queue. Unless you would like more than one linked list I would say removing the queue pointer would be a good thing to do to reduce the complexity.
peek()
here I do like what you did to do away with the need for all those paren but on first glance node *temp = *head; looks like temp == head which is far from the truth
why it is crashing recap
what peek says it does (in english):
peek takes a pointer to a pointer to a node struct
peals off the first pointer to a node
differences that pointer (with the "->" notation)
print to standard out.
substitute in what we pass to peek (in english):
peek receives NULL(0x0)
create a node struct pointer named temp and put NULL inside the pointer.
Attempt to access the address 0x0 (with the "->" notation)
segfault.
If you have any questions just ask.
Good luck :)
So I'm doing some linked list revison and Im trying to just load a list with some numbers and then print it out. Below is my code:
#include <stdio.h>
#include <stdlib.h>
typedef struct stack {
int data;
struct stack *next;
}*stack;
stack create_s(void){
stack s = (void*)malloc(sizeof(stack));
s->next = NULL;
return s;
}
void push_s(stack s, int data) {
while (s->next != NULL) {
s = s->next;
}
s->next = (void*)malloc(sizeof(stack));
s=s->next;
s->data = data;
s->next = NULL;
}
void print_s(stack s) {
if (s==NULL) {
return;
}
else {
while (s->next != NULL) {
printf("%d\n",s->data);
s=s->next;
}
}
}
int main (void) {
stack s = create_s();
push_s(s,2);
push_s(s,4);
push_s(s,6);
push_s(s,8);
print_s(s);
return 0;
}
My output is however:
-1853045587
2
4
6
when it should be
2
4
6
8
Is it printing the address of my struct at the beginning? Also, why is it not printing my last element?
Thanks
The code contains several errors, but the first thing that catches the eye is that your memory allocation is already obviously broken
stack s = (void*)malloc(sizeof(stack));
You defined stack as a pointer type. This means that sizeof(stack) evaluates to pointer size and the above malloc allocates enough space to store a single pointer, not enough for the entire struct stack object. The same memory allocation error is present in push_s as well.
Here's some advice
Don't hide pointer types behind typedef names. Define your stack as
typedef struct stack{
int data;
struct stack *next;
} stack;
and use stack * wherever you need a pointer. I.e. make that * visible instead of hiding it "inside" a typedef name. This will make your code easier to read.
Don't cast the result of malloc. Anyway, what is the point of casting it to void * when it is void * already???
Don't use sizeof with types unless you really really have to. Prefer to use sizeof with expressions. Learn to use the following malloc idiom
T *p = malloc(sizeof *p);
or, in your case
struct stack *s = malloc(sizeof *s);
This will allocate a memory block of appropriate size.
Also, as #WhozCraig noted in the comments, the very first node in your list is apparently supposed to serve as a "sentinel" head node (with undefined data value). In your code you never initialize the data value in that head node. Yet in your print_s function you attempt to print data value from the head node. No wonder you get garbage (-1853045587) as the first line in your output. Don't print the very first node. Skip it, if it really is supposed to serve as a sentinel.
Also, the cycle termination condition in print_s looks strange
while (s->next != NULL)
Why are you checking s->next for NULL instead of checking s itself? This condition will terminate the cycle prematurely, without attempting to print the very last node in the list. This is the reason why you don't see the last element (8) in your output.
The actual cause of the given output can be fixed by changing:
s=s->next;
s->data = data;
to
s->data = data;
s=s->next;