There are two aspects here in your program.
Allocation of the ::map
By declaring your variable like you did, you are creating a ::map
object in the scope of the function main()
. The map is allocated on the stack of that function and automatically initialized when that function (i.e. the function scope { .. }
) is entered.
Freeing of the ::map
Because the map was allocated on the stack when the scope was entered, it is automatically deleted when the function returns (i.e. the function scope closes). You do not need to worry about this.
What you do...
By calling the delete
operator you are trying to free memory from the process heap. The delete
operator takes as argument a pointer to the allocated memory, and by writing &mp
you are creating such a pointer. However, because the mp
object lives on the stack where you allocated it, the C++ runtime gives you the error that the pointer being freed was not allocated
on the heap using the new
operator.
Interestingly, you already have the right code in your program, you just paired the allocation/free incorrectly:
// Allocate the memory on the heap, and free it.
// mp is a pointer to the allocated map.
int main() {
std::map<int, int> *mp = new std::map<int, int>;
// do stuff, e.g. mp->insert()
delete mp;
}
// Allocate the memory on the stack, freed automatically.
// mp is a reference to the allocated map.
int main() {
std::map<int, int> mp;
// do stuff, e.g. mp.insert()
// no need to free mp explicitly!
}
Note
You may want to learn about how C/C++ programs organize their memory: heap and stack memory allocation (take a look here or here), and the difference between a pointer and a reference to a memory allocation (take a look here or here).
PS: You got lucky with the error message. In optimized code with memory safety disabled (e.g. gcc's memory sanitizer) your program would behave non-deterministically and maybe crash.