c++ - Undetected error with new operator -
i messing around trying understand pointers , operator "new"
and ended getting more confused on these 2 codes should result to, other not, wanted understand happened here. in advance.
#include <iostream> using namespace std; int main() { int * p = new int(50); p[1] = 33; cout << *p << endl; } output: 50
and when tried
#include <iostream> using namespace std; int main() { int * p = new int[50]; p[1] = 33; cout << *p << endl; } output: -842150451
i wondering meaning of each result.
in first case
int * p = new int(50); // allocates 1 int on heap, initialized value of 50 p[ 1] = 33; // p gives address of integer, // p[1] moves p pointer forward , accessing // pointed object results in undefined behavior, // means @ moment can happen // exception, crash, home war, nothing, everything, // printing garbage value
in second case:
int* p = new int[50]; // allocates 50 ints on heap, uninitialized p[ 1] = 17; // initializes element index 1 value of 17 std::cout << *p; // p gives address of first element, index 0 // still uninitialized, prints garbages
you should use
int* p = new int[50]();
to value-initialize ints 0.
Comments
Post a Comment