I guess the problem is that I have messed up the internal structures of malloc(). I haven't used free() just to be sure.
The part of code which works:
Code:
/* server program */
#include <stdio.h>
#include <stdlib.h>
#define BODY_SIZE 35
#define LOGIN_SIZE 20
typedef struct user_client {
char login[LOGIN_SIZE];
}client_user;
// the structure of the mail
typedef struct mail {
client_user sender;
client_user receiver;
char body[BODY_SIZE];
struct mail * next;
} mail;
// it's actually a pointer to the first element (header) of the structure and then
// each elements points to the next one
typedef mail *mailbox;
int main(void)
{
/* initialization */
mailbox mail_list; // a pointer to a mail
mail specific_message[2];
client_user users[2];
strncpy(users[0].login, "myle", (size_t) LOGIN_SIZE);
strncpy(users[1].login, "smyle", (size_t) LOGIN_SIZE);
// define the senders and the receivers of the mails
specific_message[0].sender = users[1]; // user1 has not received any mail
specific_message[0].receiver = users[0]; // has been sent to user2
specific_message[1].sender = users[1];
specific_message[1].receiver = users[0]; // second mail of user2
strncpy(specific_message[0].body, "lalalalalalalala", (size_t) BODY_SIZE);
strncpy(specific_message[1].body, "ta tarata tarata ta ta", (size_t) BODY_SIZE);
// each maillist contains one mail only
specific_message[0].next = &specific_message[1];
specific_message[1].next = NULL;
mail_list = &specific_message[0];
/* end of initialization */
/* the actual code begins here */
int i = 0;
for (i = 0; i < 4; i ++) // the server waits for new connections
{
printf("Iteration: %d\n", i);
mailbox sent_mail;
sent_mail = malloc(sizeof(mail));
// Debugging
//printf("The pointer value is: %x\n",sent_mail);
//printf("The address of the pointer is: %x\n", &sent_mail);
// if malloc fails
if (sent_mail==NULL){
printf("You don't have enough memory on your system. This application is going to be killed\n");
exit(1);
}
// the +1 in strlen is because of the 1 extra position required for the '\0' character
strncpy(sent_mail->sender.login, "something1", strlen("something1") + 1);
strncpy(sent_mail->receiver.login, "something2", strlen("something2") + 1);
strncpy(sent_mail->body, "something3", strlen("something3") + 1);
// the newest mail is the first one
sent_mail->next = mail_list;
mail_list = sent_mail;
// print all the mail of this user
mailbox next_mail = mail_list;
while(next_mail != NULL)
{
printf("%s user has received the mail\nbody = %s \n by %s\n\n", next_mail->receiver.login, next_mail->body,
next_mail->sender.login);
next_mail = next_mail->next;
}
}// end of loop
printf("Exit\n");
return 0;
}
but If I put it with the rest of my code, the problem makes its appearance.