Something wrong with add func - c

When I print the linked list countryName value always stay with the last string.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct usa_primaries * ptr;
typedef struct primariesDate{
int month;
int day;
int hour;
}primariesDate;
typedef struct usa_primaries{
primariesDate date;
char *countryName;
int isOpen;
ptr next;
}usa_primaries;
void add (int month, int day, int hour, char *country, int isOpen, ptr *head) {
ptr t;
t = (ptr) malloc(sizeof(usa_primaries));
t->date.month = month;
t->date.day = day;
t->date.hour = hour;
t->countryName = (char *) malloc(strlen(country)+1);
strcpy(t->countryName, country);
t->isOpen = isOpen;
if(!(*head)) {
t->next = NULL;
*head = t;
}
else {
t->next = *head;
*head = t;
}
Below is the main function, I'm trying to print only countryName details but what I see is only the last value that is inserted. for example: scanf: test1, test2 the output is: test2 test2
int main() {
ptr head = NULL;
int month, day, hour, isopen;
char country[20];
while (scanf("%d %d %d %s %d", &month, &day, &hour, country, &isopen) != EOF) {
add(month, day, hour, country, isopen, &head);
}
ptr print = head;
while (print) {
printf("\n %s ", head->countryName);
print = print->next;
}
free(head);
return 0;
}

while (print) {
printf("\n %s ", head->countryName);
// ^^^^
print = print->next;
}
You print only the head in the loop. You should print the current node:
while (print) {
printf("\n %s ", print->countryName);
// ^^^^^
print = print->next;
}

Related

segmentation fault after free-ing node in hashtable

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define size 9900
int count = 1;
struct membership {
char name[100];
char gender[100];
char code[100];
int age;
int weight;
struct membership* next;
}*table[size];
typedef struct membership member;
member *newMember(char name[], char gender[], char code[], int age, int weight){
member *node = (member*)malloc(sizeof(member));
strcpy(node->name, name);
strcpy(node->gender, gender);
strcpy(node->code, code);
node->age = age;
node->weight = weight;
node->next = NULL;
return node;
}
int asciiSum(char str[]){
int sum = 0;
for(int i = 0; str[i] != '\0'; i++){
sum += str[i];
}
return sum;
}
int hash(char code[]){
return asciiSum(code)%size;
}
// insert recursive
member *insertRec(member *curr, char name[], char gender[], char code[], int age, int weight){
if (!curr){
return newMember(name, gender, code, age, weight);
}
curr->next = insertRec(curr->next, name, gender, code, age, weight);
return curr;
}
// insert biasa
void insert(char name[], char gender[], char code[], int age, int weight){
int key = hash(code);
table[key] = insertRec(table[key], name, gender, code, age, weight);
}
void viewMember(){
printf("| %-5s | %-20s | %-20s | %-20s | %-20s | %-15s |\n",
"no", "member name", "member age", "member weight", "member gender", "member code");
int j = 0;
for (int i = 0; i < size; i++) {
member *curr = table[i];
while (curr) {
printf("| %-5d | %-20s | %-20d | %-20d | %-20s | %-15s |\n",
++j, curr->name, curr->age, curr->weight, curr->gender, curr->code);
curr = curr->next;
}
}
}
member *searchRec(member *curr, char *code){
if (!curr) return NULL;
if(!strcmp(curr->code, code))return curr;
return searchRec(curr->next, code);
}
member *deleteRec(member *curr, char *code){
if (!curr) return NULL;
if (!strcmp(curr->code, code)){
free(curr);
return curr->next;
}
curr->next = deleteRec(curr->next, code);
return curr;
}
void deleteProduct(char *code){
int key = hash(code);
member *node = searchRec(table[key], code);
if (!node) {
printf("%s not found\n", code);
return;
}
printf("Deleted %s\n", node->name);
table[key] = deleteRec(table[key], code);
}
int main(){
insert("tono", "male", "61TOM102", 21, 40);
insert("tini", "female", "61TIF102", 21, 40);
insert("didi", "male", "102DIM102", 21, 40);
deleteProduct("61TOM102");
viewMember();
return 0;
}
The code above will produce zsh: segmentation fault.
What i expected : tono node got freed and the array got printed as normal but without tono
What actually resulted : zsh: segmentation fault
i think the error is either in deleteRec function or viewMember function.
i think after i free(curr) it somehow still there but as an invalid memory ?
i'm really stumped, can someone give me a hint ?
Thank you in advance
PS. when i try running the code on online compiler there's no problem, is the problem with my hardware ?

Bus error while simply integer scanf sequence in C program

I have to take integer inputs and end the while loop if input is -1 in the following format in C:
111 1 1
111 1 1
111 1 1
-1
My code get bus error after 3rd scanf in the main function (end of the code). I know this is about white spaces but i have no idea to solve it. I am testing on MacBook with M1 if it is important. Btw print("break")s for just testing, i don't want to any junk print or scan.
#include <stdio.h>
#include <stdlib.h>
struct employee{
int ID;
int freeAt;
int totalTime;
struct employee *next;
};
struct customer{
int ID;
int startTime;
int processTime;
int waitingTime;
int helper;
struct customer *front;
struct customer *rear;
struct customer *next;
};
typedef struct employee employee;
typedef struct customer customer;
void new_employer(employee *top, int id){ //Insert employees by id
employee *ptr;
ptr = (employee*)malloc(sizeof(employee));
ptr->ID = id;
ptr->freeAt = 0;
ptr->totalTime = 0;
if (top == NULL){
ptr->next = NULL;
top = ptr;
}
else{
ptr->next = top;
top = ptr;
}
}
void help_customer(customer *c, employee *top){ //Match customer with suitable employee
employee *ptr;
ptr = (employee*)malloc(sizeof(employee));
ptr = top;
if (top==NULL){
c->startTime = c->startTime + 1;
c->waitingTime++;
help_customer(c,ptr);
}
if(c->startTime>=top->freeAt){
c->helper = top->ID;
top->freeAt = c->startTime + c->processTime;
top->totalTime = top->totalTime + c->processTime;
}
else{
help_customer(c, top->next);
}
}
void new_customer(customer *c, employee *top, int id, int start, int process){ //New customer
customer *ptr;
ptr = (customer*)malloc(sizeof(customer));
ptr->ID = id;
ptr->startTime = start;
ptr->processTime = process;
ptr->waitingTime = 0;
help_customer(ptr,top);
if (c->front == NULL){
c->front = ptr;
c->rear = ptr;
c->next = NULL;
}
else{
c->rear->next = ptr;
c->rear = ptr;
c->rear->next = NULL;
}
}
void customerStats(customer *c){ //Printing customer stats at the end of the transactions
customer *ptr;
ptr = (customer*)malloc(sizeof(customer));
ptr = c->front;
if(ptr == NULL){
printf("\nQUEUE IS EMPTY");
}
else{
printf("\n");
while (ptr!=c->rear){
printf("%d ", ptr->ID);
printf("%d ", ptr->helper);
printf("%d ", ptr->startTime);
printf("%d ", ptr->processTime);
printf("%d\n", ptr->waitingTime);
ptr = ptr->next;
}
printf("%d ", ptr->ID);
printf("%d ", ptr->helper);
printf("%d ", ptr->startTime);
printf("%d ", ptr->processTime);
printf("%d\n", ptr->waitingTime);
}
}
void employeeStats(employee *top){ //Printing employee stats at the end of the transactions
employee *ptr;
ptr = (employee*)malloc(sizeof(employee));
ptr = top;
if (top==NULL){
printf("\nSTACK IS EMPTY");
}
else{
while (ptr!=NULL){
printf("%d ", ptr->ID);
printf("%d\n", ptr->totalTime);
ptr = ptr->next;
}
}
}
int main(){
employee *e;
for(int i=1;i>7;i++){
new_employer(e,i);
}
customer *c;
int id;
int start;
int process;
while(1){ //********I GET BUS ERROR HERE ON 3RD SCANF**************
scanf("%d", &id);
printf("break1");
if (id==-1){
break;
}
scanf("%d", &start);
printf("break2");
scanf("%d", &process);
printf("break3");
new_customer(c,e,id,start,process);
}
customerStats(c);
employeeStats(e);
}
This is the terminal:
111
break11
break21
zsh: bus error ./main
It helps if you write minimal code to begin with, and get that working before adding more.
Here's a partial correction that shows why you are getting undefined behaviour (crashing). Read each line and understand why and how it differs from your code. Once that is understood, you can (cautiously, step-by-step) add one more element at a time and test, test, test as you build up toward your objective.
typedef struct employee {
int ID;
int freeAt;
int totalTime;
struct employee *next;
} employee_t;
employee_t *new_employeEEEE( employee_t *top, int id ) { //Insert employees by id
employee_t *ptr = (employee_t*)calloc( 1, sizeof(*ptr) ); // use calloc()
// Omitting check of calloc failing
ptr->ID = id;
ptr->next = top; // reverse sequence, but at least it works...
return ptr;
}
int main() {
employee_t *e = NULL;
// for( int i=1; i > 7;i++ ) !!!!
for( int i = 1; i < 7; i++ )
e = new_employeEEEE( e, i );
i = 1;
for( employee *p = e; p; p = p->next )
printf( "emp #%d has id: %d\n", i++, p->ID );
return 0;
}
Output:
emp #1 has id: 6
emp #2 has id: 5
emp #3 has id: 4
emp #4 has id: 3
emp #5 has id: 2
emp #6 has id: 1

Why doesn't my structure variable contain this member?

I wrote the following code:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int month;
int day;
int hour;
int minutes;
}primaries_date;
typedef struct
{
int all_members;
char *country;
primaries_date date;
}usa_primaries;
typedef struct node *ptr;
typedef struct node
{
usa_primaries up;
ptr next;
}Node;
void add(ptr usa_primaries *hptr, int all_members, char *con, int month, int day, int hour, int minutes)
{
ptr p;
ptr q;
ptr t;
t = malloc(sizeof(Node));
if(!t)
{
printf("Cannot build list");
exit(0);
}
t->all_members = members;
t->county = con;
t->date->month = d->month;
t->date->day = d->day;
t->date->hour = d->hour;
while( (p1) )
{
if( p->date->month >= month || p->date->day >= day || p->date->hour >= hour || p->date->minutes >= minutes )
{
q = p;
p = p->next;
}
}
if(p == *hptr)
{
*hptr = t; /*Resetting head. Assigning to the head t*/
t->next = p;
}
else
{
q->next = t;
t->next = p;
}
}
int main()
{
ptr h;
int month, day, hour, minutes;
int all_memebers; /*Declaration of all_members*/
char *county;
char member;
printf("Please enter the day");
scanf("%d",&day);
printf("Please enter the month");
scanf("%d",&month);
printf("Please enter the hour");
scanf("%d",&hour);
printf("Please enter the minutes");
scanf("%d",&minutes);
printf("Is this an all-member candidate? Y/N");
scanf("%c",&member);
if(member == 'Y')
all_members = 1;
else
all_members = 0;
printf("Please enter the country");
scanf("%s",&county);
add(&h,all_members,country,month,day,hour,minutes);
return 0;
}
I got this error:
usa.c: In function ���add���:
usa.c:42:6: error: ���struct node��� has no member named ���all_members���
t->all_members = members;
^
I don't really understand why this error occurred, since all_members is declared in the structure usa_primaries, and the structure node, contains the structure usa_primaries within it.
Why was this error displayed and how can I fix it?
Node doesn't have an all_members. It has a usa_primaries, and that has all_members. Therefore:
t->up.all_members

scanf issue multiple input

Whenever I attempt to scan in my input, example: JASON BOURNE JULY 5 1972, the program crashes.
scanf("%s %s %s %d %d", temp->fname, temp->lname, temp->month, temp->day, temp->year);
I determined it has to do with the %d's whereas if I put:
scanf("%s %s %s", temp->fname, temp->lname, temp->month);
scanf("%d %d", temp->month, temp->day);
The String values are correct and the program crashed before int's could be assigned.
Here's a copy of my struct:
typedef struct node{
char fname [29];
char lname [29];
char month [9];
int day;
int year;
struct student * next;
struct student * previous;
} student;
and here is a copy of my function in main():
student * head = malloc(sizeof(student));
student * temp = head;
int num = numStudents;
while(num != 0){
scanf("%s %s %s %d %d", temp->fname, temp->lname, temp->month, temp->day, temp->year);
printf("FUNCTION NEVER REACHES THIS POINT");
temp = temp->next = malloc(sizeof(student));
num--;
}temp->next = NULL;
Here's what I did to get everything to work if anyone is interested:
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
//Struct for Student
struct student{
char fname [29];
char lname [29];
char month [9];
int day;
int year;
struct student *next;
struct student *previous;
};
//Pre-Call
void printList(struct student *node);
struct student * insertNode(struct student * list, char fname[29], char lname[29], char month[9], int day, int year);
//Main function
int main(){
//Take Input and Assign Variables
int classes, i;
scanf("%d", &classes);
for(i = 0; i < classes; i++){
int numStudents, j;
scanf("%d", &numStudents);
struct student *list = NULL; //Create LL
int num = numStudents, day, year;
char fname[29]; char lname[29]; char month[9];
//Assign Values
while(num != 0){
scanf("%s %s %s %d %d", &fname, &lname, &month, &day, &year);
list = insertNode(list, fname, lname, month, day, year);
num--;
}
//
printList(list);
}
return 0;
}
//Function to insert a node to the LL
struct student * insertNode(struct student * list, char fname[29], char lname[29], char month[9], int day, int year){
//If the list is empty
if(list == NULL){
struct student * tempNode = (struct student *) malloc(sizeof(struct student));
strcpy(tempNode->fname,fname);
strcpy(tempNode->lname,lname);
strcpy(tempNode->month,month);
tempNode->day = day;
tempNode->year = year;
tempNode->next = NULL; // Extremely Important
return tempNode;
}
//If the list has a node
list->next = insertNode(list->next, fname, lname, month, day, year);
return list;
}
//Function to print a LL
void printList(struct student * node){
if(node->next == NULL)
printf("%s %s %s %d %d\n", node->fname, node->lname, node->month, node->day, node->year);
else
{
printf("%s %s %s %d %d\n", node->fname, node->lname, node->month, node->day, node->year);
printList(node->next);
}
}

Difference between char, char* inside Linked Lists

I created a linked list that hold int and char type data. A function adds the data to the list and the other prints it out. When i only print the int type i get no problems but when i try to also print the char type the program crashes.
So it has to do the way i'm defining the char* in the printing function print_list().
To be more specific my problem is here in print_list() :
printf("\n [%s] \n", ptr -> name);
printf("\n [%s] \n", ptr -> lastn);
So my actual code is (getting 0 errors and 0 warnings but the program crashes):
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
// Creating structure for node
struct test_struct
{
int val; // val is member id number
char name;
char lastn;
int age;
struct test_struct *next;
};
// declaring global head and curr pointers
struct test_struct *head = NULL;
struct test_struct *curr = NULL;
// creating a list
struct test_struct* create_list(int val, char* name, char* lastn, int age)
{
printf("\n creating list with head node as [%d] [%s] [%s] [%d] \n", val, name, lastn, age);
struct test_struct *ptr = malloc(sizeof(struct test_struct)); // creating list
if(NULL == ptr) {
printf("\n Node creation failed \n");
return NULL;
}
ptr->val = val;
ptr->name = *name;
ptr->lastn = *lastn;
ptr->age = age;
ptr->next = NULL;
head = curr = ptr;
return ptr;
}
// add member to list
struct test_struct* add_to_list(int val, char *name, char *lastn, int age, bool add_to_end)
{
if(NULL == head) {
return (create_list(val, name, lastn, age));
}
if(add_to_end) {
printf("\n Adding node to end of list with data [%d] [%s] [%s] [%d] \n", val, name, lastn, age);
} else {
printf("\n Adding node to beginning of list with data [%d] [%s] [%s] [%d] \n", val, name, lastn, age);
}
struct test_struct *ptr = malloc(sizeof(struct test_struct));
if(NULL == ptr) {
printf("\n Node creation failed \n");
return NULL;
}
ptr->val = val;
ptr->name = *name;
ptr->lastn = *lastn;
ptr->age = age;
ptr->next = NULL;
if (add_to_end) {
curr-> next = ptr;
curr = ptr;
} else {
ptr -> next = head;
head = ptr;
}
return ptr;
}
//printing the list
void print_list(void)
{
struct test_struct *ptr = head;
printf("\n -----Printing list Start----- \n");
while(ptr != NULL) {
printf("\n [%d] \n", ptr -> val);
printf("\n [%s] \n", ptr -> name);
printf("\n [%s] \n", ptr -> lastn);
printf("\n [%d] \n", ptr -> age);
ptr = ptr->next;
}
printf("\n -----Printing list end---- \n");
return;
}
// main function
int main(void)
{
struct test_struct *ptr = NULL;
// for adding member to list
add_to_list(123, "william", "shakespeare", 30, true);
add_to_list(124, "william", "gibson", 35, true);
add_to_list(125, "chuck", "palahniuk", 40, true);
add_to_list(126, "mario", "puzio", 50, true);
add_to_list(127, "umberto", "eco", 60, true);
add_to_list(128, "ezra", "pound", 125, true);
print_list();
return 0;
}
You have declared name and lastn as single characters
struct test_struct
{
int val; // val is member id number
char name;
char lastn;
int age;
struct test_struct *next;
};
you need to declare them either as fixed size arrays or pointers which point to allocated space to hold the strings. A string is a series of characters terminated by a \0.
struct test_struct
{
int val; // val is member id number
char name[MAXLEN];
char lastn[MAXLEN];
int age;
struct test_struct *next;
};
then copy arguments to the function to the fields in the struct
e.g.
strcpy(ptr->name,name);
strcpy(ptr->lastn,lastn);
printf("\n [%s] \n", ptr -> name);
printf("\n [%s] \n", ptr -> lastn);
%s expects char * not char as both name and lastn are char variables.
And to store name and last name of a person you should prefer char array as single char variable can't store it . Therefore , declare them as char arrays .
Example -
struct test_struct
{
int val; // val is member id number
char name[20]; // or any desired length to store a name
char lastn[20]; // similar as for name
int age;
struct test_struct *next;
};
And then to copy data in it use strncpy-
ptr->name = *name; // strncpy(ptr->name,name,strlen(name));
ptr->lastn = *lastn; // strncpy(ptr->lastn,lastn,strlen(lastn));

Resources