Please consider the following code:
struct X
{
int x1;
int x2;
};
struct Y
{
int y1;
struct X *x;
};
Now I am allocating memory dynamically as follows:
struct Y *y = new Y[N];
And for each element of this structure array, I am also allocating memory for y[i].x as follows-
y[i].x = new X[M];
In such case, how does the system will allocate memory for y before knowing the actual memory size of y[i].x.
I am getting a segmentation fault in this case. Is there any good way to allocate memory dynamically? What if I need to reallocate memory (to grow the array size dynamically)?
In such case, how does the system will allocate memory for
ybefore knowing the actual memory size ofy[i].x.
Oh, but it does know the size of y[i].x. That member's type is struct X* which is a pointer. The size of a pointer varies between architectures but it typically is 32 of 64 bits. Regardless of what X is (there are few edge cases like function pointers).
In other words X is not a piece of Y. Actually Y has a pointer that points to a chunk of memory occupied by (possibly multiple) X.
It's like having an address. You can write it down on a small piece of paper an keep it. Everyone knows the size of the paper. Regardless of how many (and how big) houses occupy the actual place.
Your segmentation fault has nothing to do with all of that. Most likely you've crossed some boundary. But it's hard to tell without the actual code.
In such case, how does the system will allocate memory for
ybefore knowing the actual memory size ofy[i].x.
The compile knowsr the size of a pointer, as x currently is declared.
The segmentation fault most probably occurs when you try to dereference y[i].x since you never correctly allocated the memory it should point to.
Is there any good way to allocate memory dynamically?
Yes there is. You should use std::vector to let it handle all the obstacles and pitfalls doing the manual memory management for you:
struct X
{
int x1;
int x2;
};
struct Y
{
int y1;
std::vector<X> x;
};
std::vector<Y> y(N);
y[i].x.resize(M);
What if I need to reallocate memory (to grow the array size dynamically)?
That will be also managed by the std::vector class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With