C order of elements in a struct

Viewed 128

I am pretty new to C and I was wondering if the order of elements in a struct matter.

I have the following struct:

struct list
{
    struct list_el *head;
    int size;
}

I use this to make a linked list. The head points to the first element and the size shows the amount of elements in the list.

I have also have the following function to initialize the list.

typedef struct list list;

list* list_init()
{
    list *list = malloc(sizeof(list));
    if(list)
    {
        list->head = NULL;
        list->size = 0;
        return list;
    }
    return NULL;
}

The program compiles fine, without any errors, warnings or notes, but when I run the program using valgrind it says I have an invalid write of size 4 on the line in the list_init() function where I assign 0 to list->size. I have the same invalid read/write every time I access the size variable. I have no idea why. Also when I switch the two struct elements around (declare size first and then head) I get the invalid write on the line where I assign NULL to head and then the size variable is used just fine. Can anybody explain me why this happens and how I can fix it?

Last note: the struct as it is shown here is defined in an header file while the function is in the C file. Not sure if this is important.

1 Answers
Related