-1

Problem:

I am trying to implement a buffer with structure queue <pair<int, int*> >. In the following code, I am trying to push 100 records in the buffer queue. After that, I am trying to pull records from the buffer again one by one:

#include <bits/stdc++.h>

using namespace std;

int main() {
    typedef int TWO_INT_ARR[2];
    typedef pair<int,int*> data_record;

    queue<data_record>* _buffer = new queue<data_record>();

    for(int i=0; i<100; ++i) {
        TWO_INT_ARR _two_int_arr;

        _two_int_arr[0] = i;
        _two_int_arr[1] = i;

        data_record     _data_record;

        _data_record.first = i;
        _data_record.second = _two_int_arr;

        _buffer->push(_data_record);
    }

    while(! _buffer->empty()) {
        data_record front_record = _buffer->front();

        cout << front_record.first << "\t"
                << front_record.second[0] << "\t"
                << front_record.second[1] << endl;

        _buffer->pop();
    }

    return 0;
}

Expected output:

0    0    0
1    1    1
2    2    2
:    :    :
99   99   99

Actual output:

0    99   99
1    99   99
2    99   99
:    :    :
99   99   99

Could anyone help me find the fault in my code ?

Ahmed Hussein
  • 715
  • 1
  • 15
  • 38
  • 3
    You stuff your queue full of dangling pointers. The local variable they point to has already been destroyed by the time you use the pointer. Your program then exhibits undefined behavior. – Igor Tandetnik Jan 05 '19 at 14:32
  • Related: https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope – drescherjm Jan 05 '19 at 14:35
  • 4
    `queue* _buffer = new queue();` why not just `queue _buffer{};`? – Fureeish Jan 05 '19 at 14:44
  • Because I need a pointer to buffer in my actual software code. Keep in mind that this is just a minimal code snippet that gives an idea about my need – Ahmed Hussein Jan 05 '19 at 14:47
  • I understood the problem, but how can I work around it ? – Ahmed Hussein Jan 05 '19 at 14:55
  • 2
    The first step is to get rid of the pointers. The second step is to switch `int TWO_INT_ARR[2]` to be `std::array` or possibly `std::pair` – drescherjm Jan 05 '19 at 15:01

1 Answers1

1

You have a big memory management issue.

First, don't use a C-style array for your data, use std::array. Then, don't use bits/stdc++.h:

typedef std::array<int, 2> TWO_INT_ARR;
typedef std::pair<int, TWO_INT_ARR > data_record;

std::queue<data_record>* _buffer = new std::queue<data_record>();

And that's it.

Also agree with @Fureeish. If this is a minimum example, then you could have just used:

std::queue<data_record> _buffer;

for this example.

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62