I’m constructing a struct with one of the member being a map.
First question is this allowed? The compiler did not complain.
struct A {
map<int, float> B;
}
Later I declare an array of such data type.
A *C = (A *)INTERNAL_CALLOC(..., sizeof(A));
Here the function INTERNAL_CALLOC is a functional wrapper of MALLOC.
Later on in the code when I try to first time insert an item into the array’s first element’s map, I got a core dump.
C[0].B[0] = 0.001;
Any idea why is this the case?
Thanks!
Yes, a map in a struct is fine.
Allocating with
mallocis definitely not fine; the constructor is not called. So your map will most likely do something terrible when you attempt to use it.General rule of thumb: don’t use
malloc/calloc/realloc/freein C++. Avoid dynamic allocation wherever possible, and usenew/deletewhen unavoidable.** And read up on smart pointers.