-2

I have a problem

struct bin
{
    int *vector;
    bin *next;
};

bin *v = new bin;

and in a function I have:

 v->vector = new int[3];
 // etc.

The idea is that: if I put v->vector[20] = 3; it's working, and I don't know why because I expected to have a error. I think i don't understand very wheel what v->vector = new int[1]; is doing .I thought it's allocated 3 int for the vector : v->vector[1],v->vector[2],v->vector[3].can someone explain to me why v->vector[20]=3;doesn't give me an error? Thanks

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97

2 Answers2

2

It's not working. It's giving "undefined behavior" - you have written into memory that you shouldn't have. C++ doesn't have array bounds checking, if you need it you'll have to do it yourself, perhaps by adding the size to the struct?

struct bin
{
    int *vector;
    int vectorSize;
    bin*next;
};

Also, C++ indexes arrays from 0, not 1, so the items you have can be accessed via: v->vector[0], v->vector[1], and v->vector[2]

Last but not least, calling it vector when there is already a very common c++ vector class may be a bit confusing. You could always look into the existing stl::vector class which may do what you need anyway.

John3136
  • 28,809
  • 4
  • 51
  • 69
-2

I assume you run your app at high level OS (Windows, Linux)? Your process will be mapped certain amount of physical memory by default.

When you did your allocation for vector[] the system allocates memory from that mapped by default physical memory (performance optimization).

When you start going via vector[] then as long as you are within valid memory address your program will not crash.

If you try to read/write vector[33776] then most probably your program will crash (most probably, since the behavior when accessing non-allocated memory is undefined).

Ivan Angelov
  • 313
  • 1
  • 7