Using malloc/realloc for array of classes/structs including std vector

后端 未结 3 999
南笙
南笙 2021-01-17 04:12

I have a question wrt malloc/realloc memory that will contain an array of class/struct (i tried both struct and class the issue remains) members that include std vectors. I

3条回答
  •  萌比男神i
    2021-01-17 04:28

    /* dynamically allocate memory */
    Comp= (voxel*)malloc(10*sizeof(voxel));
    

    Comp is now a pointer to uninitialized memory.

    for(i=0;i<10;++i) Comp[i] = v0;
    

    This attempts to call Comp[i].operator=(v0), but Comp[i] is not a valid, initialized object. In a simple test/debug case, we may get lucky but in practice we'll get garbage and the vector will either try to free/use an invalid pointer.

    That doesn't just mean you have to calloc() the memory instead, you can't make assumptions about what values an initialized object expects to find.

    /* dynamically re-allocate memory */
    Comp2= (voxel*)malloc(sizeof(voxel));  
    printf("realloc done\n");
    

    Comp2 is now a pointer to a single voxel, and no "realloc" was done.

    for(i=0;i<10;++i){
      Comp2 =(voxel*)realloc(&Comp2[0], (i+1)*sizeof(voxel));
      Comp2[i] = v0;
    }  
    

    This is just bizzare. It starts with Comp2 pointing to a single voxel. Then you for some reason take the address of the first element (&Comp2[0]) rather than just using the address of the first element (Comp2), and you reallocate it to the same size. You then copy-assign v0 into the uninitialized memory at the last-but-one position:

    Comp2 = [...uninit...]
    
    for (i  = 0
    realloc(i + 1 == 1)
    
    Comp2 = [...uninit...]
                  ^-- v0
    
    i++
    realloc(i+1 == 2)
    
    Comp2 = [.....v0.....][...uninit...]
                                ^--v0
    

    Short: You can't use malloc or calloc or realloc with non-pod objects. You might get away with it occasionally, but you are basically pointing a loaded shotgun at your foot.

    It also seems that I cannot necessarily set an initial size of a vector in a class/struct

    You can easily set the default size of a vector in a class, C++11 required (-std=c++11 or greater for gnu/clang compilers, VS2013 or higher)

    #include 
    #include 
    
    struct A {
        std::vector v = { 1, 2, 3 }; // default population
    };
    
    struct B {
        std::vector v;
        B() : v(4) {}
    };
    
    int main() {
        A a;
        B b;
        std::cout << a.v.size() << ", " << b.v.size() << "\n";
        std::cout << "\n";
        for (int v : a.v) { std::cout << v << "\n"; }
        std::cout << "\n";
        for (int v : b.v) { std::cout << v << "\n"; }
    }
    

    http://ideone.com/KA9fWB

提交回复
热议问题