The following code is part of a linked list implementation.
a) I would like your confirmation that the for loop in list_copy() will properly protect against a memory leak in case of a mem allocation error anytime during the loop execution.Code:// sllist.c #define T SLList_T typedef struct T *T; struct T { T next; void *head; }; T sllist_copy(T list) { T head, *p = &head; while (list) { *p = malloc(sizeof **p); if (!(*p)) { sllist_free(p); return NULL; } (*p)->head = list->head; p = &(*p)->next; list = list->next; } return head; } void sllist_free(T *list) { assert(list); T next; while (*list) { next = (*list)->next; free(*list); *list = next; } *list = NULL; }
b) I'd like to know if there is a way (GCC or GDB options would be fine too) for me to simulate an allocation error that could trigger during loops like the above. Some of those loops can be more complex and I'd like to test any checked and unchecked conditions on them.