0

I have been given a task to work with an ADT, I have been given it's .h file and a precompiled library of some sort that is supposed to be the implementation, however I cannot create a new instance of said ADT as the creator function always returns NULL.

/**
* Allocates a new List.
*
* Creates a new empty list. This function receives the functions which will be
* used for copying elements into the list and freeing them when needed.
* For example, in order to create a list of strings one need to define these
* two functions:
* @code
* ListElement copyString(ListElement str);
* void freeString(ListElement str);
* @endcode
* And then create a list as follows:
* @code
* List listOfStrings = listCreate(copyString, freeString);
* @endcode
*
* @param copyElement Function pointer to be used for copying elements into
* the list or when copying the list.
* @param freeElement Function pointer to be used for removing elements from
* the list.
* @return
*   NULL - if one of the parameters is NULL or allocations failed.
*   A new List in case of success.
*/
List listCreate(CopyListElement copyElement, FreeListElement freeElement);

Here are CopyListElement and FreeElement: (I'm trying to use the ADT with just a string as is required)

istElement listElementCopy(ListElement elem)
{
    char *cpy = malloc(sizeof(char)*strlen(elem) + 1);

    for(int i = 0; i < strlen(elem); i++)
        cpy[i] = ((char *)elem)[i];

    cpy[strlen(elem)] = '\0';

    return cpy;
}

void listElementFree(ListElement elem)
{
    free(elem);
}

Here is the test I ran to determine that the ADT was returning NULL:

int main()
{
    List result = listCreate(listElementCopy, listElementFree);
    if(result == NULL)
        printf("Fail\n");
}

more relevant info:

/** Type for defining the list */
typedef struct List_t *List;

/** Type used for returning error codes from list functions */
typedef enum ListResult_t {
    LIST_SUCCESS,
    LIST_NULL_ARGUMENT,
    LIST_OUT_OF_MEMORY,
    LIST_INVALID_CURRENT,
} ListResult;

/** Element data type for list container */
typedef void* ListElement;

/**
* Type of function for copying an element of the list.
*
* Such a function should be supplied to a list to allow it to copy its
* elements. The function supplied should be able to dynamically copy the
* object and return a pointer to a newly allocated object.
* If this function fails for some reason, it should return NULL.
*
* For example, here is a proper function for copying a string that can be
* used for storing strings in a list:
* @code
* ListElement copyString(ListElement str) {
*   assert(str);
*   char* copy = malloc(strlen(str) + 1);
*   return copy ? strcpy(copy, str) : NULL;
* }
* @endcode
*/
typedef ListElement(*CopyListElement)(ListElement);

/** Type of function for deallocating an element of the list */
typedef void(*FreeListElement)(ListElement);
Tom
  • 69
  • 7

0 Answers0