Search code examples
cmemoryreturnfree

First return than free char value c


In this function I need to return AND remove a char value (free the allocated memory). What is wrong with this function?

char* pqueue_poll(PrioQueue *queue) {
        if (queue->root == NULL) {
            return "NULL";
        }

        else {
            char* name = (char *) malloc(sizeof(char)*10);
            q_elem *temp = queue->root;

            name = temp->name;      
            queue->root = queue->root->next;

            return name;

            free(temp);
            free(&temp->name);
        }
    }

I tryed first to free and than to return it but no result, I have some error with valgrind. I have also a separate function (without deleting) that returns the value I want to return and remove here


Solution

  • Here is a couple of major problems with you code

    • name = temp->name; will just set char *name to point at the string you want to return. You need to do memcpy and then free the memory.
    • free after return never will get executed

    I guess what you want is

    1. Allocate memory for return data (or use static array)
    2. Copy the data from the queue
    3. Free memory in the queue structure
    4. Return the pointer (which one would have to free later if you didn't use static buffer for it)