Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does using arrays in C++ result in security problems

Tags:

c++

security

I was told that the optimal way to program in C++ is to use STL and string rather than arrays and character arrays.

i.e.,

vector<int> myInt;

rather than

int myInt[20]

However, I don't understand the rational behind why it would result in security problems.

like image 558
segfault Avatar asked Dec 21 '25 02:12

segfault


2 Answers

I suggest you read up on buffer overruns, then. It's much more likely that a programmer creates or risks buffer overruns when using raw arrays, since they give you less protection and don't offer an API. Sure, it's possible to shoot yourself in the foot using STL too, but at least it's harder.

like image 160
unwind Avatar answered Dec 22 '25 16:12

unwind


There appears to be some confusion here about what security vectors can and cannot provide. Ignoring the use of iterators, there are three main ways of accessing elements ina vector.

  • the operator[] function of vector - this provides no bounds checking and will result in undefined behaviour on a bounds error, in the same way as an array would if you use an invalid index.

  • the at() vector member function - this provides bounds checking and will raise an exception if an invalid index is used, at a small performance cost

  • the C++ operator [] for the vector's underlying array - this provides no bounds checking, but gives the highest possible access speed.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!