Reputation: 314
I tried to allocate dynamic memory for an array of empty queues using the malloc function, as the code shows. However, the output of (*pq).size()
is incorrect -128, and calling (*pq).push()
will cause an error. Where did I go wrong? How to allocate the memory correctly?
#include <stdio.h>
#include <stdlib.h>
#include <queue>
typedef std::queue<int> iq;
iq *pq;
int main() {
pq = (iq *) malloc(16 * sizeof(iq));
printf("%d\n", (*pq).size());
printf("%d\n", (*pq).empty());
// (*pq).push(12);
(*pq).pop();
printf("%d\n", (*pq).size());
free(pq);
return 0;
}
Upvotes: 2
Views: 1311
Reputation: 238391
How to allocate memory for an array of queues by malloc?
Just like you did in your example. Technically, it's not the allocation that's wrong. Although, see †.
Where did I go wrong?
You only allocated some amount of memory for the queues. You never constructed any queue object into that block of memory. Dynamic objects are constructed using a new-expression. To construct an object into a block of memory allocated by malloc
, you could use the placement-new syntax.
How to allocate the memory correctly?
By not using malloc
.
† There is no good reason to use malloc
in C++.
Here is a correct way to allocate dynamic memory for an array of 16 queues, as well as construct those queues:
std::vector<std::queue<int> > pq(16);
The vector will take care of numerous problems that you would shoot yourself in the foot otherwise. It will take care of constructing the elements as well as destroying them, avoids memory leaks and double removes, as well as more subtle issues like exception safety.
Upvotes: 4
Reputation: 5386
It's not clear if malloc
is a requirement of your solution. A native C++ solution avoids most of the issues with readable semantics. See below.
In the code below, I've switched to using iostream
and vector
, as it frees you to reason about everything at the same level of abstraction. Malloc
is a low-level C routine for allocating dynamic memory. You're already using std::queue
, so it doesn't really make sense to mix malloc
when a vector
will do just fine.
#include <queue>
#include <iostream>
#include <vector>
using iq = std::queue<int>;
using vec = std::vector<iq>;
int main()
{
using namespace std;
vec pq;
pq.resize(16);
pq[0].empty();
cout << pq[0].size() << endl;
pq[0].push(12);
pq[0].push(13);
pq[0].push(11);
pq[0].pop();
cout << pq[0].size() << endl;
return 0;
}
$main
0
2
Upvotes: 0