I am not very good at C++ and I currently porting some piece of code to C. It allocates a big array of objects like this:
o_list::Node** nodes = (o_list::Node**)malloc(SIZE*sizeof(o_list::Node*)); and then fills each position with:
for(int u=0;u<SIZE;u++) nodes[u] = new o_list::Node(); From what I understand, the only assurance we have regarding contigous memory is that the pointers to the objects are in fact contiguous, i.e. it might 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 correct this, I tried to malloc the first array (of pointers) and then malloc an array of objects, and then assign the pointers to the right positions, like this:
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 fault. I would like to know if my assumption is correct and why I have a segmentation fault in the second option.
Thanks