YamHon.CHAN
YamHon.CHAN

Reputation: 886

CPP: Mysterious error for array initialization and crash?

My program seems to always produce ridiculous errors. Please provide directions for me. The following code segment cutout all irrelevant parts. Thanks.

Part A of the code segment seems failed to initialize the array correctly, how to debug? Part B of the code segment always crash, is there anything i missed?


typedef unsigned long T_PSIZE;
int main()
{
   int AG_TOTAL = 6 ;
   /* part A1 */
   T_PSIZE* cntPeopleByAge = new T_PSIZE[AG_TOTAL + 1];
   /* part A2 - originally i use static array like this, but it also fails */
   //T_PSIZE cntPeopleByAge T_PSIZE[AG_TOTAL + 1];
   for (int i = 0; i < (AG_TOTAL + 1); i++)
   {
     std::cout << i << ":" << cntPeopleByAge[i] << "\t";
     cntPeopleByAge[i] = 0;
     std::cout << cntPeopleByAge[i] << "\n";
   }
   std::cout << "cntPeopleByAge:" << cntPeopleByAge[ AG_TOTAL + 1 ] << "\n";
   /* part B */
   delete [] cntPeopleByAge;
   return 0; // <---  crash here!
}

Sample Output

0:200320        0
1:201581        0
2:201582        0
3:201583        0
4:0     0
5:0     0
cntPeopleByAge:1799119387:0:0

Upvotes: 0

Views: 184

Answers (2)

Jeff D.
Jeff D.

Reputation: 328

/* Sorry. but that earlier answer is not correct. The loop correctly starts at zero and ends at < the limit. The problem is that you are declaring an array of pointers, but never allocating memory to the objects that they point to. Your output is showing you addresses not numbers. One way is to allocate the objects as you use them (you must delete them individually as well) */

T_PSIZE* cntPeopleByAge = new T_PSIZE[AG_TOTAL + 1];    
for (int i = 0; i < (AG_TOTAL + 1); i++)    
{ 
cntPeopleByAge[i] = new T_PSIZE();
}

What you really want to use is the vector class in the standard library which handles all of this for you:

#include <vector>

std:vector<T_PSIZE *> cntPeopleByAge;
cntPeopleByAgex.resize(AG_TOTAL + 1);

Good luck ...

Upvotes: -1

jrok
jrok

Reputation: 55395

for (int i = 0; i < (AG_TOTAL + 1); i++)
   {
     std::cout << i << ":" << cntPeopleByAge[i] << "\t";
     //                       ^^^^^^^^^^^^^^^^
     // You're reading uninitialized memory here

     cntPeopleByAge[i] = 0;
     std::cout << cntPeopleByAge[i] << "\n";
   }

And here

std::cout << "cntPeopleByAge:" << cntPeopleByAge[ AG_TOTAL + 1 ] << "\n";

you're going out of bounds. The last valid index is AG_TOTAL.

You've got undefined behaviour (UB). The errors are only as ridiculous as UB can be.

Upvotes: 5

Related Questions