You haven't really asked a question, but a couple of issues I can see with the code are:
char *mymsg[1028];
...
mymsg[1] = "serving for sender\n";
Here you have mymsg
which is an array of 1028
pointers to char
, which is intended to be treated as a string. (By the way, why 1028? Not that it matters, but just so you know 2^10 is 1024). However, this array contains pointers that are not initialized and are pointing to random locations. Important thing is, there is no space allocated for the possible message you want to put in them.
Second issue is that arrays in C start with index 0, so you probably meant to write
mymsg[0] = "serving for sender\n";
That doesn't matter however.
More importantly, you can't copy strings in C using =
, you should use strcpy
and copy to a memory location that you have already allocated. Here are two ways to do it:
char mymsg[1028][1028]; // if you are sure your messages fit in 1028 chars
...
mymsg[1] = malloc(strlen("serving for sender)*sizeof(char)); // sizeof(char) not really needed
strcpy(mymsg[1], "serving for sender\n");
msgsnd(msqid,mymsg[1],len,msgflg);
free(mymsg[1]);
or
char *mymsg[1028];
...
char str_to_be_printed[] = "serving for sender\n";
mymsg[1] = malloc(strlen(str_to_be_printed)*sizeof(char)); // sizeof(char) not really needed
strcpy(mymsg[1], str_to_be_printed);
msgsnd(msqid,mymsg[1],len,msgflg);
free(mymsg[1]);
Edit: In the second case where you already have the string somewhere (and not in the form of "this is a string"), assigning the pointers is enough and you don't to copy or allocate memory. However, if your situation is more complex than this, and between assignment of mymsg[1] = ...
and msgsnd
there are other code, you have to make sure the original string stays alive until msgsnd
is done. Otherwise, you have a dangling pointer which will cause you problems. Here's the idea:
+-+-+-+-+-+-+-+-+--+
str_to_be_printed ----->|A| |s|t|r|i|n|g|\0|
+-+-+-+-+-+-+-+-+--+
^
mymsg[1]---------------/
If you free
the memory of str_to_be_printed
, access to mymsg[1]
would cause segmentation fault/access violation.
Note that, the code I wrote is just to give you a guideline, don't copy-paste it.