index violation?

Please see some sample code at http://sourcemaking.com/design_patterns/flyweight/cpp/2

This is an example of the flyweight design pattern. I realize, the main point is the pattern, and not CPP itself, which is fine. However, some of the code still raises some CPP questions for me.

In the FlyweightFactory class there's an array of pointers to icons w dimension 5. So valid indexes go from 0 to 4. However, if you keep calling FlyweightFactory::getIcon with new and different names, seems like the index can become invalid (larger than 4)?

If array index becomes invalid, this does NOT automatically result in an exception but behavior is undefined? I thought it was an automatic exception, but when I modify the code slightly to get the array index to become invalid, it seems to not be the case.

Thanks for any assistance.

No, accessing out of bounds just means you are accessing memory you do not own. It has undefined behavior by standard, that means anything can happen: access violation, access to other variable memory, nasal demon spawning, anything.

This is why you should not use raw arrays and pointers. Use managed containers and make sure that no code path can lead to undefined behavior without causing proper error condition.
Yes, I use containers myself. I was just following this sample code and it led me to this investigation of what actually happens with invalid indexes. I recall seeing exceptions triggered in such cases, so I thought that would always be the case. But I see that that was not a correct conclusion. The result is just undefined.

I was REALLY surprised by what it actually did in this case when the index went out of bounds. It masked the error and would have made debugging in denser code more of a headache.
. I recall seeing exceptions triggered in such cases
It was probably debug library enabled. It is created exactly for this: to enable some checks in debug mode.

It masked the error
It is not an error in first case. Accessing address X is not an error. However it might raise problems and lead to error if this memory was not given to program in first place (OS will not know what physical memory will correspond this virtual memory address). All cases of accessing invalid memory is undefined behavior. That means anything can happen: you do not know haow memory is accessed and what operations are made, and you just applied those operations to some data which is not suited for this. Also there is some optimisations depending on that UB does not happens.
Topic archived. No new replies allowed.