0

I have created an array of strings in struct and it is shared.

the struct is as following :

struct data{
    int uids[5];
    int sockids[5];
    int stat[30];
    char msgs[30][1024];
};

this is the writing part and i can see the string on printf.

for (int i = 0; i < bufSize; i++) {
    if ((*d).stat[i] == -1) {
        (*d).stat[i] = sockid;
        memset(&((*d).msgs[i][0]), 0, strlen(d->msgs[i]));
        strncpy((*d).msgs[i], buf,1023);
        printf("\nwriting for me %d %s\n",sockid,d->msgs[i]);
        return 1;
    }
}

for reading from the same area :

for(int i=0;i<bufSize;i++){
    if((*d).stat[i]==mysocket){
        (*d).stat[i]=-1;
        printf(" message for me %d  %d %s\n",mysocket,d->stat[i],d->msgs[i]);
        fflush(stdout);
        send(mysocket,(*d).msgs[i],strlen((*d).msgs[i]),0);
        memset(&((*d).msgs[i][0]), 0, strlen(d->msgs[i]));
    }
}

in the reading part i get blank sometimes...

sample output.. :

writing for me 6 36753 : sending some message

message for me 6 -1

sometimes the message comes and sometimes its blank. Can anyone please point out what is the error.

  • 1
    `memset(&((*d).msgs[i][0]), 0, strlen(d->msgs[i]));` - what would `strlen(d->msgs[i])` be here, given `d->msgs[i]` is uninitialized (or you don't show any initialization code here)? – Eugene Sh. Jan 24 '18 at 16:34
  • what is `bufsize`? We cannot reproduce the problem from the posted code snippets. Please post a [mcve] – user3629249 Jan 24 '18 at 16:48
  • regarding: `(*d).stat[i]=-1; printf(" message for me %d %d %s\n",mysocket,d->stat[i],d->msgs[i]);` the field `(*d).stat[i]` is set to -1, so that is what is output for the third parameter of the call to `printf()` – user3629249 Jan 24 '18 at 16:56
  • regarding: `printf(" message for me %d %d %s\n",mysocket,d->stat[i],d->msgs[i]); fflush(stdout);` because the last item in the format string is `\n`, which flushes `stdout`, the call to `fflush()` has no effect and can be removed. – user3629249 Jan 24 '18 at 16:58
  • one obvious problem is that the field `mysocket` contains -1. when printing the info. I.E. The source of the problem is NOT in the posted code. Please post a [mcve]. – user3629249 Jan 24 '18 at 17:04
  • @EugeneSh. thanks that was the issue. i hardcoded it now to its full value of 1024. it maybe taking some garbage. You can post it as the answer i will accept. – Ashwin Bhoyar Jan 24 '18 at 17:05
  • in general, this: `d->stat[i]` is much easier to follow than `(*d).stat[i]` Strongly suggest picking one format and sticking with it. – user3629249 Jan 24 '18 at 17:05
  • @user3629249 i will try to upload it on github or somewhere – Ashwin Bhoyar Jan 24 '18 at 17:06
  • @user3629249 thanks for the feedbacks it would really improve the coding style and reduce my errors in future – Ashwin Bhoyar Jan 24 '18 at 17:07

0 Answers0