Linked list in a key-release-event callback results in a free error

Here’s the thing. I have a linked list struct that I’d like to use in a key-release-event callback.
But every time I put the constructor inside the callback function and the callback gets executed, the app crashes and a free error show up in my terminal.

Here’s the constructor.

   information *new_information ()
          information *new;
          new = malloc (sizeof (new));
          new->name = malloc (sizeof (new->name));
          new->value = malloc (sizeof (new->value));
          new->prev = NULL;
          new->next = NULL;
          return (new);

The error only occurs if I put the constructor inside the callback or any function inside it.
If I initialize the list outside, everything executes perfectly. Kind of.
Every time I pass the list as a gpointer argument, it adds a bunch of random stuff in the beginning but that’s not a problem.
It also only does that when I initialize the next element. If I don’t use the next element, it works just fine. But I kinda need that for something.

I already tried using GList and putting my struct inside the data field but it complicates a ton of stuff.

I’d really appreciate if there’s a way I could use my linked list in the callback.

This has nothing to do with the callback, or GTK thereof.

Your new_information allocator just doesn’t do what you think. In C, sizeof(new) gives you the size of new. new is a pointer to something (information here), so it gives you the size of the pointer not what it points to – and that’s the issue you have.

Additionally, the malloc(sizeof(new->something))are again very unlikely to be what you want. If information::name is merely a pointer to e.g. a string, don’t allocate anything yet and you’ll assign a pointer later. If it’s a pointer data structure that does need allocation, you have the same issue than in the first allocation (allocating the size of the pointer), but then you should also review whether it’s a good way to do things (but then again, I think you’re likely wanting the first scenario and assign a pointer later).

You should review how pointers, allocation and sizeof works a bit to be sure it’s clear in your head. Yeah, C is pretty hard at first, but pretty basic once everything becomes clear.

1 Like

:grin: Thank you so very much!
I would give you a big hug if I could right now. I’ve been stuck on that for hours. Just dereferencing the pointer did the trick.

Thanks again! :grin:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.