It looks like you have a problem with newlines while pasting the code.
Here is a reformated version:
Code:
#include
#include
#include
typedef struct data {
int no;
char *payload;
} message;
void new_message(message *msg, int no, char *str);
int main(int argc, char** argv)
{
message msg1, msg2;
char *str1 = "hello", *str2 = "world!";
new_message(&msg1, 1, str1);
new_message(&msg2, 2, str2);
printf("msg1 no: %d\n", msg1.no);
printf("msg1 payload: %s\n", (&msg1)->payload);
printf("msg2 no: %d\n", msg2.no);
printf("msg2 payload: %s\n", (&msg2)->payload);
return 0;
}
void new_message(message *msg, int no, char *str)
{
msg = malloc(sizeof(msg));
msg->payload = malloc(sizeof(char) * (strlen(str)+1) );
strncpy(msg->payload, str, strlen(str));
msg->no = no;
printf("no in function: %d, payload in function: %s\n", msg->no, msg->payload);
}
void print_message(void *m)
{
message *msg;
msg = (message *) m;
printf("Thread %d owns %s\n", msg->no, msg->payload);
}
Now to the problems.
You define msg1 and msg2 in main.
This means you have place for two struct message on stack.
Then you give the address of the struct to a function, this is okay.
But in the function, you allocate memory and want asign the address to this pointer.
This will not work because the pointer is a fixed address to an struct in stack.
One solution is that you declare msg1 and msg2 as a pointer in main.
Code:
int main(int argc, char** argv)
{
message *msg1 = NULL, *msg2 = NULL;
char *str1 = "hello", *str2 = "world!";
new_message(&msg1, 1, str1);
new_message(&msg2, 2, str2);
printf("msg1 no: %d\n", msg1->no);
printf("msg1 payload: %s\n", msg1->payload);
printf("msg2 no: %d\n", msg2->no);
printf("msg2 payload: %s\n", msg2->payload);
return 0;
}
Second, malloc can fail and you receive a NULL pointer.
Check allways the returned value of malloc.
Your function can look like this:
Code:
int new_message(message **msg, int no, char *str)
{
if (msg && *msg == NULL) {
*msg = malloc(sizeof(**msg));
if (*msg == NULL) {
printf("Ooops!\n");
return -1;
}
}
if ((*msg)->payload == NULL) {
(*msg)->payload = malloc(strlen(str) + 1);
if ((*msg)->payload == NULL) {
printf("Ooops!\n");
free(*msg);
return -1;
}
}
strncpy((*msg)->payload, str, strlen(str));
(*msg)->no = no;
printf("no in function: %d, payload in function: %s\n", (*msg)->no, (*msg)->payload);
return 0;
}
Changes:
The funktion return an integer, so the caller can check if it is successfull.
The returned values from malloc will be checked.