Hello there
I'm progressing through a project with chained lists.
I made a bunch of utility functions to handle this type of structure as described in the project instructions :
Code:
typedef struct s_list
{
struct s_list *next;
void *data;
} t_list;
I went to test my code, and made a header that included this structure :
Code:
typedef struct s_list
{
void *data;
struct s_list *next;
} t_list;
This made my code misbehave in a way I really really don't understand. Example of a function to create an element :
Code:
#include "ft_list.h"
t_list *ft_create_elem(void *data)
{
t_list *new;
new = malloc(sizeof(*new));
if (new == NULL)
return (NULL);
new->next = NULL;
new->data = data;
return (new);
}
Example of a function to add an element to the front of a list :
Code:
#include "ft_list.h"
void ft_list_push_front(t_list **begin_list, void *data)
{
t_list *new;
if (! begin_list)
return ;
new = ft_create_elem(data);
if (new == NULL)
return ;
new->next = *begin_list;
*begin_list = new;
}
As you can see, absolutely unremarkable, unoriginal functions which use ->next and ->data as you'd expect them to.
However, when coupled with my header file, this kind of wizardry happened :
Code:
new element address: 0x7fffea3ba2a0
new->data is: 0x7ffff2595952
list address: 0x7fffea3ba2a0
list->data: (nil)
list->next: 0x7ffff2595952
Only after I rectified my header to have next first and data second did the code work as intended :
Code:
new element address: 0x7fffebec12a0
new->data is: 0x7ffff44bc8a2
list address: 0x7fffebec12a0
list->data: 0x7ffff44bc8a2
list->next: (nil)
I compiled 3 c files together like this :
Code:
./main.c
./ex00/ft_create_elem.c
./ex01/ft_list_push_front.c
By using
Code:
gcc (my 3 files) -I .
To indicate to gcc that the header it was to use was located where I was... but I had several header files like this :
Code:
./ft_list.h
./ex00/ft_list.h
./ex01/ft_list.h
I would assume the problem was that several header files were being included... BUT I protected them adequately with
Code:
#ifndef FT_LIST_H
# define FT_LIST_H
[...]
#endif
What the hell happened here? I don't understand.