N
Neil Zanella
Hello,
When an "std::map<int, int> foobar;" statement appears in a C++ program
followed by a statement of the form "foobar[123];" where nothing has ever
been inserted at position 123 into map foobar, the C++ standard states
that a new element is created at position 123 and is initialized to
zero. That is, in this case, the pair (123, 0) is inserted into the
map.
I am interested in knowing what the standard says should happen in the
following case. Does the standard mandate that struct Foo's pointers be
initialized to zero as well, upon reference to hello[110], or does this
program lead to undefined behavior.
Thank you for your feedback and explanations,
Neil
#include <iostream>
#include <map>
struct Foo {
int *x;
int *y;
};
typedef std::map<int, Foo> Hello;
int main() {
Hello hello;
//initialize entiry structure, hence also its pointers, to zero
//(I believe this is according to the ANSI/ISO C++ standard too)
std::cout << hello[110].x << std::endl;
//hence dereferencing zero memory address causes segfault
//std::cout << *hello[110].x << std::endl;
//hence same goes for assigning
*hello[110].x = 112;
}
When an "std::map<int, int> foobar;" statement appears in a C++ program
followed by a statement of the form "foobar[123];" where nothing has ever
been inserted at position 123 into map foobar, the C++ standard states
that a new element is created at position 123 and is initialized to
zero. That is, in this case, the pair (123, 0) is inserted into the
map.
I am interested in knowing what the standard says should happen in the
following case. Does the standard mandate that struct Foo's pointers be
initialized to zero as well, upon reference to hello[110], or does this
program lead to undefined behavior.
Thank you for your feedback and explanations,
Neil
#include <iostream>
#include <map>
struct Foo {
int *x;
int *y;
};
typedef std::map<int, Foo> Hello;
int main() {
Hello hello;
//initialize entiry structure, hence also its pointers, to zero
//(I believe this is according to the ANSI/ISO C++ standard too)
std::cout << hello[110].x << std::endl;
//hence dereferencing zero memory address causes segfault
//std::cout << *hello[110].x << std::endl;
//hence same goes for assigning
*hello[110].x = 112;
}