queue not working as expected

Hi everybody,
my simplified console application code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
...
queue<char*> pQCh;
...
void thread1(void *data);
...
void main() {
  ...
  _beginthread(thread1, 0, (void*)&data);
  ...
}
void thread1(void *data) {
  ...
  char *buffer;
  ...
  while(condition) {
    retval = recv(socket, buffer, ...);
    pQCh.push(buffer);
  }
  while(!pQCh.empty()) {
    cout<<pQCh.front();
    pQCh.pop();
  }
  ...
}


And, if I send, let's say this imput:
aaa
bbb
ccc

then the output here is not as expected (the same as input), but like this:
ccc
ccc
ccc


More interesting if i try to output in recv loop it outputs the element just received, not the first (as i think should be). If i output not front, but back element, it is the same as front always. The structure itself works perfectly for example codes from MSDN. What am I doing wrong? Thanks.
Last edited on
You're queing a pointer to a buffer, then overwritting the buffer each time. If you're processing strings, you can use a queue of strings instead: std::queue<std::string>
You're treating a primitive char pointer as if it were a string object.
Make the queue a queue<string> and replace the push line with pQCh.push(string(buffer,retval));

Please note that this won't work properly if you receive any null bytes, that you don't check the return value of recv to see if the connection has been reset aaaand that main has to be declared as int main().
Last edited on
I don't honestly recall what recv does, but I assume it doesn't allocate space for buffer, and that allocation is omitted in the above. Keep in mind buffer isn't a 'string' - it's a pointer to an array of characters. My guess is you are pushing that pointer onto your queue 3 times, and recv is overwriting the data that buffer points to. Before your 2nd loop, try adding
buffer[0] = 'x'
I suspect you'll see "xcc" 3 times in your output.

To fix, you probably want to re-allocate buffer before each read, and delete when you pop(). Or, to make it even classier, push boost::shared_ptr's onto the queue for each buffer allocated in this way. That way it gets deleted for you automagically :)
Thank you guys, it helped much :)
I used string for queue type and it worked. Also i added few lines to substr the actual message from whole buffer.
Topic archived. No new replies allowed.