2

I want to create a function that adds an element to the end of a linked list. It also has to return 0 if the element was added successfully, or a 1 if memory could not allocated/saved to for the element.

The question is, how do I know if the memory was allocated successfully or if the element was added successfully? This is the code:

int push_back(pos_t *head, int new_value) {
    pos_t *temp = head;

    while (temp->next != NULL) {
        temp = temp->next;
    }
    pos_t *temp1 = (pos_t *)malloc(sizeof(pos_t));
    temp1->data = new_value;
    temp1->next = NULL;
    temp = temp1;
}
2
  • temp=temp1; --> temp->next = temp1; ? Commented Oct 23, 2017 at 21:29
  • Is head == NULL possible? It would be useful to see how the link-list is initialized. Commented Oct 23, 2017 at 21:49

2 Answers 2

1

You need to add the following code

if (temp1 == NULL) { return 1; }

because malloc is defined to either return a pointer to the allocated memory, or

  • if the size is zero, return NULL.
  • on error, return NULL.

You can control that you don't request a size of zero, so if you used a positive size, and malloc returned NULL, you can deduce an error occurred.

Many systems have "manuals" installed. If you are using a Linux system, the command "man malloc" will pull up the manual page for malloc. If you are working on a Windows system, a web search for the manual for malloc will give you enough detail to handle the details.

Sign up to request clarification or add additional context in comments.

1 Comment

Of course, you'll need to add a return 0; too, and the locations of both code additions are left for you to figure out.
0

The function has a shortcoming: it cannot be used to allocate the first node in the list, ie if the list is empty.

The prototype should be changed to

int push_back(pos_t **headp, int new_value);

passing the address of the list pointer instead of its value.

Testing for malloc() failure is simple: juts compare the returned pointer to NULL or 0.

Here is the corresponding code:

int push_back(pos_t **headp, int new_value) {
    pos_t *temp = *headp;
    pos_t *temp1 = malloc(sizeof(pos_t));
    if (temp1 == NULL) {   // allocation failure
        return 1;
    }
    temp1->data = new_value;
    temp1->next = NULL;

    if (temp == NULL) {      // empty list
        *headp = temp1;
    } else {
        while (temp->next != NULL) {
            temp = temp->next;
        }
        temp->next = temp1;  // append node to the end of the list
    }
    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.