C ++ objects contiguous in memory?

I am not very good at C ++, and I am moving part of the code to C. It allocates a large array of such objects:

o_list::Node** nodes = (o_list::Node**)malloc(SIZE*sizeof(o_list::Node*));

and then fills each position:

for(int u=0;u<SIZE;u++)
   nodes[u] = new o_list::Node();

From what I understand, the only certainty we have regarding continuous memory is that pointers to objects are actually contiguous, i.e. it may happen that we have:

 _____________________
|x||x||x||x||x||x||x|x| -> contiguous array of pointers;
 |   \ \         
 |    \ \______
 |     \       \
 O      O       O       -> not contiguous positions of objects;

To fix this, I tried to malloc the first array (of pointers), and then the malloc array of objects, and then assign the pointers to the correct positions, for example:

o_list::Node** nodes = (o_list::Node**)malloc(SIZE*sizeof(o_list::Node*));

o_list::Node* contObjs = (o_list::Node*)malloc(SIZE*sizeof(o_list::Node));

for(int u=0;u<SIZE;u++){
   contObjs[u] = o_list::Node();
   nodes[u] = &contObjs[u];
}

But this leads to a segmentation error. I would like to know if my assumption is correct and why I have a segmentation error in the second option.

thank

+4
3

, ( ). , .

, , , - SIZE 300000, . SIZE ?

+1

, .

, , :


o_list::Node  objArray[SIZE];
o_list::Node* ptrArray[SIZE];

for (int i=0; i<SIZE; i++)
    ptrArray[i] = objArray+i;

o_list::Node* objArray = malloc(SIZE*sizeof(o_list::Node));
o_list::Node* ptrArray[SIZE];

for (int i=0; i<SIZE; i++)
    ptrArray[i] = objArray+i;

o_list::Node   objArray[SIZE];
o_list::Node** ptrArray = malloc(SIZE*sizeof(o_list::Node*));

for (int i=0; i<SIZE; i++)
    ptrArray[i] = objArray+i;

o_list::Node*  objArray = malloc(SIZE*sizeof(o_list::Node));
o_list::Node** ptrArray = malloc(SIZE*sizeof(o_list::Node*));

for (int i=0; i<SIZE; i++)
    ptrArray[i] = objArray+i;
+1

++, new, ? - ?

MyClass * arrayOfMyClass = new MyClass[5];

" C, C ". , C . malloc, Node C. , malloc() C, new.

new . malloc . , , , . C , , . C- :

void Node_init(struct Node* aNode)
{
    // Any initialisation you need to do of its members
}

...

struct Node* contObjs = malloc(SIZE * sizeof *contObjs); // or use calloc to get zero filled memory

for(int u=0;u<SIZE;u++) {
   Node_init(&contObjs[u]); // Pass the address of the u'th element
}
0

All Articles