From: J. G. <jg-...@jg...> - 2004-04-29 18:29:02
|
Hi, on the 29/04/04 16:12, Michael Gerdau wrote: >> #include <iostream> >> int main (void) >> { >> int x; >> int *y = new int; >> std::cout << x << y; >> delete y; >> return 0; >> } >> >> What should it print? Zeros? Anything it wants? > > For x definitely anything it wants. Unless x ends up in the .bss section (which depends on compilation and linking specifics), you could check this using objectdump and looking at the symbol. BSS section is zeroed upon load by expansion, as these are all considered 0. > For y I could imagine the memory to be initialized with 0. The new operator is just simple memory allocation wrapper (likely even just malloc in many cases), and malloc does not set to zero. You could create a "new" which did zero, it would be like this: void * operator new_cleared(std::size_t size) throw (std::bad_alloc) { void * result = calloc(size, 1); // if calloc was unable to allocate and clear (NULL returned), // then throw exception // (could check errno to be sure!) if (result != NULL) { throw std::bad_alloc(); } return result; }; // this is untested You could even create a "renew" operator too, as C++ lacks this because they prefer the use of containers instead of functions and classes managing their own memory. A renew operator could work with a realloc() style allocator. Kind regards JG |