Lock-free queue - c

Also I am doing a c implementation and currently have the structure of the queue:
typedef struct queueelem {
queuedata_t data;
struct queueelem *next;
} queueelem_t;
typedef struct queue {
int capacity;
int size;
queueelem_t *head;
queueelem_t *tail;
} queue_t;
queue_t *
queue_init(int capacity)
{
queue_t *q = (queue_t *) malloc(sizeof(queue_t));
q->head = q->tail = NULL;
q->size = 0;
q->capacity = capacity;
return q;
}
int CompareAndExchange (void **a, void *comparand,void *new) {
int success = 0;
pthread_mutex_lock(&CE_MUTEX);
if ((*a) != comparand) {
(*a) = new;
//return TRUE
success = 1;
}
pthread_mutex_unlock(&CE_MUTEX);
//return FALSE
return success;
}
But not sure How to continue, with queue and dequeue functions...
How would the code look like?

Sometime ago, I've found a nice solution to this problem. I believe that it the smallest found so far.
The repository has a example of how use it to create N threads (readers and writers) and make then share a single seat.
I made some benchmarks, on the test example and got the following results (in million ops/sec) :
By buffer size
By number of threads
Notice how the number of threads do not change the throughput.
I think this is the ultimate solution to this problem. It works and is incredible fast and simple. Even with hundreds of threads and a queue of a single position. It can be used as a pipeline beween threads, allocating space inside the queue.
The repository has some early versions written in C# and pascal. Im working to make something more complete polished to show its real powers.
I hope some of you can validate the work or help with some ideas. Or at least, can you break it?

Your pseudo-code can (and most likely does) suffer from the ABA problem, as only the pointer is checked, and not an accompanying unique stamp, you'll find this paper of use in that regard and as a general guide to lock-free queue implementation, with its pitfalls.
When dealing with lock free programing, its also a good idea to read up on Herb Sutter's works, as He gives good, insightful explanations to whats required, why its required and its potential weak points (though beware that some of his older publications/articles where found to contain some hidden/unforseen problems).

and also the recent boost'con talk about this subject :
https://github.com/boostcon/2011_presentations/raw/master/wed/lockfree_2011_slides.pdf

(Leaving this here for now, but see edit.)
Do you know a implementation of lock free queue in C?
I wrote lockless queue recently (http://www.ideone.com/l2QRp). I can't actually guarantee it works correctly, but I can't find any bugs and I've used it in a couple of single threaded programs without any problems, so there's nothing too obvious wrong with it.
Trivial usage example:
queue_t queue;
int val = 42;
queue_init(&queue,sizeof val);
queue_put(&queue,&val);
val = 0;
queue_pop(&queue,&val);
printf("%i\n",val); // 42
queue_destroy(&queue);
Edit:
As #Alexey Kukanov pointed out, queue_pop can fail if tmp is popped,freed,allocated again, and put again between checking for null and swapping:
if(!tmp->next) return errno = ENODATA;
/* can fail here */
} while(!sync_swap(q->head,tmp,tmp->next));
I'm not yet sure how to fix this, but I'll (hopefully) update this once I figure it out. For now, disregard this.

You may try this library it is built in c native. lfqueue
For Example
int* int_data;
lfqueue_t my_queue;
if (lfqueue_init(&my_queue) == -1)
return -1;
/** Wrap This scope in other threads **/
int_data = (int*) malloc(sizeof(int));
assert(int_data != NULL);
*int_data = i++;
/*Enqueue*/
while (lfqueue_enq(&my_queue, int_data) == -1) {
printf("ENQ Full ?\n");
}
/** Wrap This scope in other threads **/
/*Dequeue*/
while ( (int_data = lfqueue_deq(&my_queue)) == NULL) {
printf("DEQ EMPTY ..\n");
}
// printf("%d\n", *(int*) int_data );
free(int_data);
/** End **/
lfqueue_destroy(&my_queue);

Related

static initialization of queue

I'm working on a high-reliance implementation of an algorithm for an embedded system.
in main.c:
//.. in main()
int queue_buffer[QUEUE_LEN + 1] = { 0 };
Queue queue;
queue_init(&queue, QUEUE_LEN, queue_buffer);
do_things_on_queue(&queue);
//.. in main()
in queue.c:
void queue_init(Queue *q, int len, int *data) {
q->head = 0;
q->tail = 0;
q->len = len;
q->data = data; // an array of length `len + 1`
}
in queue.h:
typedef struct queue {
int head;
int tail;
int len;
int *data;
} Queue;
I would like to 1. have main.c to not know about Queue; and 2. not use malloc for intializing queue_buffer_ but rather do it statically.
this implies that ideally main.c would be:
//.. in some function
Queue *queue = queue_init(something_eventually);
do_things_with_queue(queue);
//.. in some function
Is it possible to modify queue_init in queue.cto achieve this in C99? If so, what's the best approach?
Tentative Solutions
I am aware of the technique discussed in this post yet they seems unfeasible without using malloc. I know for sure that I will simultaneously have 4 queues at most. This makes me think that I could declare a memory pool for the queues as a static global array of queues of size 4. Is it ok to use global variables in this case?
#KamilKuk suggested to just have queue_init to return the structure itself since QUEUE_LEN is known at compile time. This requires the following:
in queue.c:
Queue queue_init(void) {
Queue q;
q.head = 0;
q.tail = 0;
q.len = QUEUE_LEN;
for (int i=0; i < QUEUE_LEN; i++)
q.data[i] = 0;
return q;
}
in queue.h:
typedef struct queue {
int head;
int tail;
int len;
int data[QUEUE_LEN];
} Queue;
Queue queue_init(void);
This appears to greatly simplify the structure initialization.
However this does not solve the privacy problem, since main.c should know about Queue to initialize this struct.
Thank you.
I would like to 1. have main.c to not know about Queue; and 2. not use
malloc for intializing queue_buffer_ but rather do it statically.
this implies that ideally main.c would be:
//.. in some function
Queue queue = queue_init(something_eventually);
do_things_with_queue(&queue);
//.. in some function
No, your objectives do not imply a solution as described. You cannot declare or use an object of type Queue anywhere that the definition of that type is not visible. That follows directly from the language's rules, but if you want a more meaningful justification then consider that even if main does not access any of the members of Queue, it still needs the definition simply to know how much space to reserve for one.
It's not obvious to me that it serves a useful purpose to make type Queue opaque in main.c (or anywhere), but if that's what you want then in that scope you can forward declare it, never define it, and work only with pointers to it:
typedef struct queue Queue;
// ...
Queue *queue = queue_init(something_eventually);
do_things_with_queue(queue);
For that to work without dynamic memory allocation, the pointed-to Queue objects must have static storage duration, but that does not mean that they need to be globals -- either in the sense of being accessible via a name with external linkage, or in the sense of being declared at file scope.
Additionally, you have the option of allocating the data arrays automatically, as in your example code, so as to not tie up that memory in queues when they are not in use. If you prefer, you can wrap that up in a macro or two for a bit of additional ease of use (left as an exercise).
For example,
queue.h
typedef struct queue Queue;
Queue *queue_init(int queue_size, int queue_data[]);
void queue_release(Queue *queue);
queue.c
#include "queue.h"
struct queue {
int head;
int tail;
int len;
int *data;
};
Queue *queue_init(int queue_len, int queue_data[]) {
// queue_pool has static storage duration and no linkage
static Queue queue_pool[4] = {{0}};
// Find an available Queue, judging by the data pointers
for (Queue *queue = queue_pool;
queue < queue_pool + sizeof(queue_pool) / sizeof(*queue_pool);
queue++) {
if (queue->data == NULL) {
// This one will do. Initialize it and return a pointer to it.
queue->head = 0;
queue->tail = 0;
queue->len = queue_len;
queue->data = queue_data;
return queue;
}
}
// no available Queue
return NULL;
}
void queue_release(Queue *queue) {
if (queue) {
queue->data = NULL;
}
}
main.c
// ... in some function
int queue_data[SOME_QUEUE_LENGTH];
Queue *queue = queue_init(SOME_QUEUE_LENGTH, queue_data);
do_things_with_queue(queue);
queue_release(queue);
// ...
Of course, if you prefer, you can put the queue data directly into the queue structure, as in your tentative solution, and maybe provide a flag there to indicate whether the queue is presently in use. That would relieve users of any need to provide storage, at the cost of tying up the storage for all the elements of all the queues for the whole duration of the program.
The best way to do this is to pass a buffer and its size to the init function, exactly as you already have.
It is a very bad idea to worry about calling a function versus having the data fixed at compile time. Both the execution time and code size for a tiny initialization like this is negligible. Making your code interface awkward just to save a few instructions at startup is not just a waste of effort, it makes the code hard to maintain and risks introducing bugs.
There are a number of embedded systems or libraries that provide a macro which declares both the storage array and the control structure in one go and gives them a name which is known only to the library, and then you have to use a macro to generate the name every time you access the item. For an example of this you might look at osMailQDef in CMSIS-OS. I don't really recommend this method though. It is too easy to get wrong, whereas doing it the usual way is easy to read and any reviewer will be able to spot a mistake straight away.
I would typically do:
// queue.h
#define QUEUE_INIT(data, len) { .len = len, .data = data }
#define QUEUE_INIT_ON_STACK(len) QUEUE_INIT((char[len]){0}, len)
// main.c
static Queue queue = QUEUE_INIT_ON_STACK(QUEUE_LEN + 1);
As for PIMPL idiom, it's easy to implement with descriptors just like file descriptors in LINUX, especially when the count is static.
// queue.h
typedef Queue int;
void do_things_with_queue(Queue);
// queue.c
struct RealQueue { stuff; };
static struct RealQeueue arr[4] = { stuff };
static struct RealQeueue *get_RealQueue(Queue i) {
assert(0 <= i && i < sizeof(arr)/sizeof(*arr));
return &arr[i];
}
void do_things_with_queue(Queue i) {
struct RealQueue *queue = get_RealQueue(i);
}
// main.c
static Queue queue = 1;
// etc.
Or you can break all hell and synchronize alignment between source and header file:
// queue.h
struct Queue {
// This has to be adjusted __for each compiler and environment__
alignas(60) char data[123];
};
#define QUEUE_INIT() { 0xAA, 0xBB, etc.. constant precomputed data }
// queue.c
struct RealQeueue { stuff; };
static_assert(alingof(struct RealQueue) == alignof(struct Queue), "");
static_assert(sizeof(struct RealQueue) == sizeof(struct Queue), "");
void do_things_with_queue(Queue *i) {
struct RealQueue *queue = (struct RealQueue*)i->data;
}

How to handle malloc failing and returning NULL?

I'm a bit confused on how to check if a memory allocation failed in order to prevent any undefined behaviours caused by a dereferenced NULL pointer.
I know that malloc (and similiar functions) can fail and return NULL, and that for this reason the address returned should always be checked before proceeding with the rest of the program. What I don't get is what's the best way to handle these kind of cases. In other words: what is a program supposed to do when a malloc call returns NULL?
I was working on this implementation of a doubly linked list when this doubt raised.
struct ListNode {
struct ListNode* previous;
struct ListNode* next;
void* object;
};
struct ListNode* newListNode(void* object) {
struct ListNode* self = malloc(sizeof(*self));
if(self != NULL) {
self->next = NULL;
self->previous = NULL;
self->object = object;
}
return self;
}
The initialization of a node happens only if its pointer was correctly allocated. If this didn't happen, this constructor function returns NULL.
I've also written a function that creates a new node (calling the newListNode function) starting from an already existing node and then returns it.
struct ListNode* createNextNode(struct ListNode* self, void* object) {
struct ListNode* newNext = newListNode(object);
if(newNext != NULL) {
newNext->previous = self;
struct ListNode* oldNext = self->next;
self->next = newNext;
if(oldNext != NULL) {
newNext->next = oldNext;
oldNext->previous = self->next;
}
}
return newNext;
}
If newListNode returns NULL, createNextNode as well returns NULL and the node passed to the function doesn't get touched.
Then the ListNode struct is used to implement the actual linked list.
struct LinkedList {
struct ListNode* first;
struct ListNode* last;
unsigned int length;
};
_Bool addToLinkedList(struct LinkedList* self, void* object) {
struct ListNode* newNode;
if(self->length == 0) {
newNode = newListNode(object);
self->first = newNode;
}
else {
newNode = createNextNode(self->last, object);
}
if(newNode != NULL) {
self->last = newNode;
self->length++;
}
return newNode != NULL;
}
if the creation of a new node fails, the addToLinkedList function returns 0 and the linked list itself is left untouched.
Finally, let's consider this last function which adds all the elements of a linked list to another linked list.
void addAllToLinkedList(struct LinkedList* self, const struct LinkedList* other) {
struct ListNode* node = other->first;
while(node != NULL) {
addToLinkedList(self, node->object);
node = node->next;
}
}
How should I handle the possibility that addToLinkedList might return 0? For what I've gathered, malloc fails when its no longer possible to allocate memory, so I assume that subsequent calls after an allocation failure would fail as well, am I right? So, if 0 is returned, should the loop immediately stop since it won't be possible to add any new elements to the list anyway?
Also, is it correct to stack all of these checks one over another the way I did it? Isn't it redundant? Would it be wrong to just immediately terminate the program as soon as malloc fails? I read that it would be problematic for multi-threaded programs and also that in some istances a program might be able to continue to run without any further allocation of memory, so it would be wrong to treat this as a fatal error in any possible case. Is this right?
Sorry for the really long post and thank you for your help!
It depends on the broader circumstances. For some programs, simply aborting is the right thing to do.
For some applications, the right thing to do is to shrink caches and try the malloc again. For some multithreaded programs, just waiting (to give other threads a chance to free memory) and retrying will work.
For applications that need to be highly reliable, you need an application level solution. One solution that I've used and battle tested is this:
Have an emergency pool of memory allocated at startup.
If malloc fails, free some of the emergency pool.
For calls that can't sanely handle a NULL response, sleep and retry.
Have a service thread that tries to refill the emergency pool.
Have code that uses caching respond to a non-full emergency pool by reducing memory consumption.
If you have the ability to shed load, for example, by shifting load to other instances, do so if the emergency pool isn't full.
For discretionary actions that require allocating a lot of memory, check the level of the emergency pool and don't do the action if it's not full or close to it.
If the emergency pool gets empty, abort.
How to handle malloc failing and returning NULL?
Consider if the code is a set of helper functions/library or application.
The decision to terminate is best handled by higher level code.
Example: Aside from exit(), abort() and friends, the Standard C library does not exit.
Likewise returning error codes/values is a reasonable solution for OP's low-level function sets too. Even for addAllToLinkedList(), I'd consider propagating the error in the return code. (Non-zero is some error.)
// void addAllToLinkedList(struct LinkedList* self, const struct LinkedList* other) {
int addAllToLinkedList(struct LinkedList* self, const struct LinkedList* other) {
...
if (addToLinkedList(self, node->object) == NULL) {
// Do some house-keepeing (undo prior allocations)
return -1;
}
For the higher level application, follow your design. For now, it may be a simple enough to exit with a failure message.
if (addAllToLinkedList(self, ptrs)) {
fprintf(stderr, "Linked List failure in %s %u\n", __func__, __LINE__);
exit(EXIT_FAILURE);
}
Example of not exiting:
Consider a routine that read a file into a data structure with many uses of LinkedList and the file was somehow corrupted leading to excessive memory allocations. Code may want to simply free everything for that file (but just for that file), and simply report to the user "invalid file/out-of-memory" - and continue running.
if (addAllToLinkedList(self, ptrs)) {
free_file_to_struct_resouces(handle);
return oops;
}
...
return success;
Take away
Low level routines indicate an error somehow. Higher level routines can exit code if desired.

What to return from function that returns a struct type in case of error? [duplicate]

This question already has answers here:
Error handling in C code
(23 answers)
Closed 4 years ago.
I'm implementing a queue in C and, following general advice of using as little dynamic memory as possible, have the following for my nodes:
struct qnode {
struct message_t message;
struct qnode* next;
};
struct message_t {
char prefix[BUF_SIZE];
char command[CMD_MAXLEN];
char params[MAX_PARAMS][BUF_SIZE];
};
Since I'm only dealing with message_ts and not pointers to them, my dequeue function has the following signature:
struct message_t dequeue(struct message_q* q);
Is there a convention on what to return from this type of function if there is an error (in my case, what if the queue is empty)? For now, I'm returning a struct message_t with all fields set to "0".
My other alternative would be to use pointers to message_t everywhere, and then return NULL in case of error. I'd like to know the pros and cons of each approach, as well as some of the best practices in my specific case.
This won't be a complete solution for you, but something like this would be very re-usable going ahead.
I have a small task (not in RTOS context) handler for a non-OS based uController firmware. I prefer it done this way. Suppose I have a set of functions which add/delete tasks to a queue, checks if queue is full/empty, check if task is present in the queue or not, etc.
typedef enum {
Q_SUCCESS = 1,
Q_FULL,
Q_EMPTY,
Q_TASKDUPLICATE,
Q_TASKNOTFOUND,
MAX_QSTATES,
Q_FAILURE = -1,
} eQStates_t ;
eQStates_t Queue_AddTask(eTasks_t Task);
eQStates_t Queue_DiscardTask0(void);
bool_t Queue_GetOccurance(eTasks_t Task);
To give you an example of how they are being used, lets pick a function.
eQStates_t Queue_DiscardTask0(void)
{
uint32_t iLoop = 0;
// Check if the count is zero, should never be the case as an Idle task is always there, adding itself into the queue
if(0 == Queue_GetCount())
{
return Q_EMPTY;
}
// Discard the position 0 Task from the queue
// Shift the whole queue
// Add Idle task to the end of the queue
return Q_SUCCESS;
}
I agree that this isn't a very intelligent code to set as an example, but may be this could give an idea about how you could use the similar kind of implementation.

C/Multithreading /Segmentation fault / (May be) Issue with queue for the threads

I am trying to create thread library.For this I am trying to implement queue to store the pending threads to be executed.
#include <ucontext.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct {
ucontext_t context;
}MyThread;
#define MAX 20
MyThread queue[MAX];
int rear=0,front=0;
void addToQueue(MyThread t)
{
if(rear==MAX)
{
printf("Queue is full!");
return;
}
queue[front]=t;
front+=1;
}
MyThread* removeFromQueue()
{
if(front==rear)
return NULL;
rear=rear+1;
return &(queue[rear-1]);
}
MyThread umain;
void MyThreadInit (void(*start_funct)(void *), void *args)
{
getcontext(&(umain.context));
char p[64000];
umain.context.uc_stack.ss_sp =(char *)p;
umain.context.uc_stack.ss_size = sizeof(p);
umain.context.uc_link =NULL;
makecontext(&umain.context,(void(*)(void))start_funct,1,args);
setcontext(&(umain.context));
}
MyThread MyThreadCreate (void(*start_funct)(void *), void *arg)
{
MyThread newthread;
char args[10000];
getcontext(&(newthread.context));
newthread.context.uc_stack.ss_sp =(char *)args;
newthread.context.uc_stack.ss_size = sizeof(args);
newthread.context.uc_link =NULL;
makecontext(&newthread.context,(void(*)(void))start_funct,1,arg);
addToQueue(newthread);
return newthread;
}
void MyThreadYield(void)
{
MyThread* a=removeFromQueue();
MyThread save;
if(a != NULL)
{
printf("Before yielding the context \n");
getcontext(&(save.context));
addToQueue(save);
//swapcontext(&umain.context,&(a->context));
setcontext(a);
printf("After the swapping the context \n");
}
else
{ printf("NULL!!! \n");
}
}
void func1(void *arg)
{
printf("func1started \n");
MyThreadYield();
}
void func2(void *arg)
{
printf("func2started \n");
MyThreadYield();
}
void func12(void *arg)
{
printf("func12started \n");
MyThreadCreate(func1,arg);
MyThreadCreate(func2,arg);
MyThreadYield();
}
int main(void)
{
int i=0;
printf("inside the main function \n");
MyThreadInit(func12,&i);
return 0;
}
Output :
inside the main function
func12started
Before yielding the context
func1started
Before yielding the context
func2started
Before yielding the context
func1started
Before yielding the context
Segmentation fault
The reason I mentioned the queue because i tried experimenting by removing below code from 'MyThreadYield' function and it workes fine but doesnt do the intended functionality.
getcontext(&(save.context));
addToQueue(save);
For one, your queue implementation is not thread-safe at this point. Your question strongly suggests that this code will be used in a multi-threaded environment. Having a non thread-safe queue will give you wrong results, and weird things can happen (like removeFromQueue() returning the same thing to two different threads, or addToQueue() inserting two items in the same position).
Aside from that, your queue implementation would never work. You are not using front and rear correctly. Look carefully at the insert function:
void addToQueue(MyThread t)
{
if (rear==MAX)
{
printf("Queue is full!");
return;
}
queue[front]=t;
front+=1;
}
You check if rear is MAX, yet, you write into queue[front] and increment front. What if I just keep adding items to the queue, eventually reaching the buffer's limit? rear will always be 0, front will grow indefinitely, and your function will write beyond the limits of queue. That's probably the cause of your segmentation fault errors.
I think you wanted to check for front instead:
void addToQueue(MyThread t)
{
if (front == MAX)
{
printf("Queue is full!");
return;
}
queue[front]=t;
front+=1;
}
The code for removeFromQueue() looks superficially ok, as long as queue is a global array (since you're returning a pointer, and can't return pointers to local variables). However, the single, most important fact you have to take out of this answer, is that your queue implementation will not scale in the long-term. An array-based queue is a terrible choice. What do you do when you run out of space in the array? What if I insert MAX elements, then remove 2 or 3, and try to insert more? Your code will say the queue is full, because it only ever allows you to insert MAX elements in total. You could shift every element in the queue to the left when an element is removed, but that's crazy, and extremely inefficient. Or you could increment front modulo MAX, allowing rear to be ahead of front, as long as you know that no more than MAX elements can be inserted. That would be better, but it would break the logic in removeFromQueue(), since the pointers returned earlier will possibly point to a different thread struct as you manipulate the queue - total disaster. Definitely not what you want.
A much, much better approach would be to implement this with a linked list where you keep a pointer to the head and a pointer to the tail. Have a look at http://en.wikipedia.org/wiki/Queue_(abstract_data_type)#Queue_implementation

How to use free on a handle inside a list?-> C -> windows API

I have a list in C that is something like this:
typedef struct _node
{
int number;
DWORD threadID;
HANDLE threadH;
struct *_node next;
} *node;
And you have somthing like this:
node new_node = malloc(sizeof(node));
As you may have guessed out, this list will store information for threads, including their handlers and Id's. Still I am having trouble when I try to do this:
free(new_node);
Everytime I try to do this I encounter an unexpected error, VS saying that there was a data corruption. I've pinned down as much as possible and I found that the problem resides when I try to use free the handle.
I've searched on MSDN how to do this but the only thing I can find is the function that closes the thread (which is not intended here, since I want the thread to run, just deleting it's record from the list).
The question is: how I am supposed to free an handle from the memory? (Considering that this is only a copy of the value of the handle, the active handle is not being deleted).
EDIT: This is the function to insert nodes from the list:
int insereVisitanteLista(node* lista, DWORD threadID, HANDLE threadH, int num_visitante)
{
node visitanteAnterior;
node novoVisitante = (node)malloc(sizeof(node));
if(novoVisitante == NULL)
return 0;
novoVisitante->threadID = threadID;
novoVisitante->threadH = threadH;
novoVisitante->number = num_visitante;
novoVisitante->next = NULL;
if(*lista == NULL)
{
*lista = novoVisitante;
return 1;
}
visitanteAnterior = *lista;
while(visitanteAnterior->next != NULL)
visitanteAnterior = visitanteAnterior->next;
visitanteAnterior->next =novoVisitante;
return 1;
}
And this is the function to delete nodes:
int removeVisitanteLista(node * lista, DWORD threadID)
{
node visitanteAnterior = NULL, visitanteActual;
if(*lista == NULL)
return 0;
visitanteActual = *lista;
if((*lista)->threadID == threadID)
{
*lista = visitanteActual->next;
visitanteActual->next = NULL;
free(visitanteActual);
return 1;
}
while(visitanteActual != NULL && visitanteActual->threadID != threadID)
{
visitanteAnterior = visitanteActual;
visitanteActual = visitanteActual->next;
}
if (visitanteActual == NULL)
return 0;
visitanteAnterior->next = visitanteActual->next;
free(visitanteActual);
return 1;
}
What exactly is a node that you are trying to free? Is this a pointer to a struct _node? If yes, have you allocated it previously? If no, free is not needed, otherwise you have to check if node is not NULL and make sure you do not free it multiple times. It is hard to guess what you are doing and where is an error without a minimal working example reproducing the problem. The only thing I can suggest is to read about memory management in C. This resource might help.
UPDATE:
node in your code is a pointer to _node. So sizeof (node) is a size of a pointer, which is either 4 or 8 bytes (depending on architecture). So you allocate 8 bytes, for example, but assume you have a pointer to the structure which is much larger. As a result, you corrupt memory, and behavior of the program becomes undefined. So changing node novoVisitante = (node)malloc(sizeof(node)) to node novoVisitante = (node)malloc(sizeof(_node)) should fix the problem.
You haven't shown us the context of your call to free() so I need to speculate a little but my first concern is that you didn't mention removing the node from the list before deleting it.
Start by unlinking the node by modifying the next field of the previous (or head) node. If you still get the error, then you have corrupted memory somehow by writing past the end of one of your allocated memory structures or something similar.
Also, I assume node is a pointer. You really haven't provided much information about what you're doing.

Resources