As you can see from the images attached below, adding the second element from the top of the list create a strange behaviour for the printf function.
the function that add a list node is:
void add_QUEUEnode_top(Item a)
{
if (head==NULL)
{
QUEUEinit(a);
}
else
{
QUEUEput_top(a);
}
return;
}
void QUEUEinit(Item a)
{
head=(link)malloc(sizeof(link*));
head->next=NULL;
head->item=a;
tail=head;
printf("Coda iniziallizata...\n\n");
}
void QUEUEput_top(Item a)
{
link tmp;
tmp=(link)malloc(sizeof(link*));
tmp->item=a;
tmp->next=head;
head=tmp;
return;
}
Here the functions that handle the items:
Item fill_item()
{
Item a;
int i;
for(i=0; i<DIM-1; i++)
{
a.stringa[i]=rand();
}
a.stringa[DIM-1]='\0';
a.numero=rand();
printf("\nOggetto generato: \n");
print_item(a);
return a;
}
void print_item(Item a)
{
printf("\nStringa elemento: ");
printf("%s", a.stringa);
printf("\nNumero elemento: %d\n", a.numero);
}
Here's the link to the codeblock project i'm editing. The function print_item(Item a)
that call the "bugged" printf is in the item.c
module, while the functions that generate a list item are inside the list.c
module.
Any idea of what can cause this problem?
PS: i'm sorry for the captures located in italian
EDIT: definition of the items:
typedef struct
{
char stringa[DIM];
int numero;
} Item;
Definition of the link pointer:
typedef struct QUEUEnode *link;
definition of the link structure:
struct QUEUEnode
{
Item item;
link next;
};
link
andItem
? I'll note that the lines that look likehead=(link)malloc(sizeof(link*));
are suspicious. Casting to a different type than the size you used? Actually, the cast isn't even required at all in C, but the fact that you needed to do a crazy one is a bit more telling....malloc(sizeof(link*))
does not allocate what you think it does. It allocate memory enough for a pointer (i.e. 4 or 8 bytes) which most likely will not be enough for yourlink
structure.