I have this linked list node struct that's using a zero-length array for storing memory:
typedef struct s_list
{
size_t *list_size;
struct s_list *prev;
struct s_list *next;
size_t size;
char data[0];
} t_list;
(list_size is a pointer containing the size of the total list)
And I'm using this function to allocate a new node:
static t_list *lst_new_element(void *data, size_t size)
{
t_list *new_element;
new_element = malloc(sizeof(t_list) + size);
if (!new_element)
return (NULL);
new_element->size = size;
memcpy(new_element->data, data, size); // <--- Segfault occurs here
return (new_element);
}
So the segmentation fault occurs in the memcpy, but I don't understand why because I allocate sizeof(t_list) + size bytes so this should be enough to do a memcpy(size) on data.
The segfault occured with this call: lst_new_element((void *)atoll(argv[1]), sizeof(long long)) (argv[1] is 5)
Thanks for the help.
5(argv[1]) represents a valid address to read in your environment? (For example, user binaries in xv6 will allow that)argv[1]is"5"(it's written in the post)[]- not[0]char arr[1];as last member, then wildly converting that into some pointer or accessing it out of bounds. This was known as "the struct hack" and was a common source of strange bugs and broken code. Afaik gcc invented zero-length arrays as a cure against "the struct hack", somewhere in the mid-90s.