Solve the four problems included in the second document. Make sure you attend the master session with them fully understood.
In the following session you will use these concepts to solve a memory management problem, thus you may use these solutions to answer correctly the questions.
Check with these questions if you understood this document
Choose the errors found in each piece of code.
1 2 3 4 5 6 7 8 9 10 11 12 | int count_element(int id, struct list *inicio) { int cont=0; struct list *aux= (struct list *) malloc (sizeof(struct list)); aux=inicio; while (aux!=NULL) { cont++; aux=aux->next; } return cont; } |
1 2 3 4 5 6 7 8 9 10 11 12 | int count_element(int id, struct list **inicio) { int cont=0; struct list *aux; aux=*inicio; while (*inicio!=NULL) { cont++; *inicio=(*inicio)->next; } return cont; } |
1 2 3 4 5 6 7 8 9 10 11 12 | int count_element(int id, struct list *inicio) { int cont; struct list *aux; aux=inicio; while (aux!=NULL) { cont++; aux=aux->next; } return cont; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | struct list *del_element(int id, struct list *inicio) { struct list *aux,*ant; aux=inicio; ant=inicio; while ((aux!=NULL)&&(aux->id!=id)) { ant=aux; aux=aux->next; } if (aux == NULL) return inicio; if (aux == ant) { free(aux); inicio=inicio->next; } else { ant->next=aux->next; free(aux); } return inicio; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | struct list *del_element(int id, struct list *inicio) { struct list *aux,*ant; aux=inicio; while ((aux!=NULL)&&(aux->id!=id)) { ant=aux; aux=aux->next; } if (aux == NULL) return inicio; if (aux == ant) { inicio=inicio->next; free(aux); } else { ant->next=aux->next; free(aux); } return inicio; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | struct list *del_element(int id, struct list *inicio) { struct list *aux,*ant; aux=inicio; ant=inicio; while ((aux!=NULL)&&(aux->id!=id)) { ant=aux; aux=aux->next; } if (aux == NULL) return inicio; if (aux == ant) { inicio=inicio->next; free(aux); } else { ant->next=aux->next; } return inicio; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | struct vector *create_vector(int number) { if (number == 0) return NULL; struct vector *nuevo= (struct vector *) malloc(sizeof(struct vector)*number); if (nuevo == NULL) return NULL; int i=0; while (i<=number) { nuevo[i]=i; i++; } return nuevo; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | struct vector *create_vector(int number) { if (number == 0) return NULL; struct vector *nuevo= (struct vector *) malloc(sizeof(struct vector)*number); if (nuevo == NULL) return NULL; int i; while (i<number) { nuevo[i]=i; i++; } return nuevo; } |