Question: Segmentation fault (core dumped) error and not sure why. Most likely from the insertList function. PLEASE HELP!! Instructions: Objectives: Linked list, struct pointer Specification: In

Segmentation fault (core dumped) error and not sure why. Most likely from the insertList function. PLEASE HELP!!

Instructions:

Objectives: Linked list, struct pointer Specification: In this lab, five functions need to be implemented/modified based on the prelab. 1. List *initList(): this function initializes the linked list. 2. int insertList(List **): this function inserts a new node containing a Rect pointer in front of the current linked list. 3. void printList(List *): this function prints out the area of each rectangle in the current linked list. 4. List* freeList(List *): this function frees all the allocated memories in the current linked list. 5. float averageArea(List *): this function computes the average of all rectangle areas and returns the result as a float number. My code:

# include # include # include

// define structs typedef struct { int height; int width; } Rect;

typedef struct list { Rect *r; struct list *next; } List;

List *initList(); int insertList(List **); void printList(List *); List* freeList(List *); float averageArea(List *);

int main() {

// random function srand(time(NULL));

List* list = initList(); int check = 0; for (int i = 0; i < 10; i++){ check = insertList(&list); if (check == -1){ printf("Insufficient memory "); return -1; } } printList(list);

float aveArea = averageArea(list); printf("Average area is %.2f ",aveArea);

list = freeList(list);

return 0; }

// function to initialize linked list List * initList() { List * p; p = (List *)malloc(sizeof(List)); // if successful malloc if(p) { p->next = NULL; } return p; }

// function inserts new node containing a Rect pointer in front of current linked list int insertList (List **first) { List* p; p = (List *)malloc(sizeof(List)); Rect* rec; rec = (Rect *)malloc(sizeof(Rect)); if(!p) return (-1); else { p->r->width = rec->width; p->r->height = rec->height; p->next = *first; *first = p; return 0; } }

// prints out area of each rectangle in current linked list void printList(List *l) {

List *p = l; printf(" Areas are: "); while(p != NULL) { printf("%d, ", (p->r->width)*(p->r->height)); p = p->next; } }

// computes average of all rectangle areas and returns result as float number float averageArea(List *l) { float totalArea = 0.0; List *p = l; while(p != NULL) totalArea += ((p->r->width)*(p->r->height)); return (totalArea/10); }

// free list List* freeList(List *l) { List *temp; while(l != NULL) { temp = l; l = l->next; free(temp); } return(l); }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!