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

后端 未结 3 996
南笙
南笙 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:34

    It's probably nothing to do with the realloc. Your code already has undefined behaviour when you do this near the start:

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

    Comp[0] has never been initialized (since malloc returns uninitialized memory -- it cannot know what type you intend to use it for and so could not possibly initialize it even if it wanted to). Then your code attempts to assign to it. This is not permitted for complex types like vector.

    Why is it not permitted? In the case of vector, because when you assign to a vector that already holds data, it needs to free the old data. If there's nothing to free then it would free nothing. But uninitialized memory might have any values at all, so it may well appear to vector that there is something which should be freed, that in fact is not a freeable pointer at all, let alone something that vector should be freeing as a consequence of that assignment. Without initialization, some class invariant along the lines of "this pointer data member is always either a null pointer or else is the address of some memory that is the vector's responsibility" is violated and so the vector code does not work.

    Supposing that your code somehow makes it past this point, you still can't realloc memory containing a vector. From the point of view of the standard, this is because vector is not a POD type, and so byte-by-byte copies of it (including that done by realloc) result in undefined behavior.

    From the point of view of a particular implementation, we might ask ourselves what code the implementer might write, which would go wrong in the case that vectors are copied byte-for-byte. One hypothetical answer is that in some circumstances the vector could contain a pointer into its own body (as part of a so-called small vector optimization) [Edit: actually, I think a small vector optimization isn't possible within the standard for other reasons, but my general point is that because vectors are not POD, the implementer is free to use their creativity]. If the vector is relocated then this pointer no longer points into the vector's own body and so the class invariants are not satisfied, and the code no longer works. To give implementers freedom to write code like this, your freedom as a user of the class is limited, and you are not permitted to relocate a vector (or in general any non-POD type) by byte-wise copying.

提交回复
热议问题