1

I am studying C++ reading Stroustrup's book that in my opinion is not very clear in this topic (arrays). From what I have understood C++ has (like Delphi) two kind of arrays:

Static arrays that are declared like

int test[3] = {10,487,-22};

Dynamic arrays that are called vectors

std::vector<int> a;

a.push_back(10);
a.push_back(487);
a.push_back(-22);

I have already seen answers about this (and there were tons of lines and concepts inside) but they didn't clarify me the concept.


From what I have understood vectors consume more memory but they can change their size (dynamically, in fact). Arrays instead have a fixed size that is given at compile time.

In the chapter Stroustrup said that vectors are safe while arrays aren't, whithout explaining the reason. I trust him indeed, but why? Is the reason safety related to the location of the memory? (heap/stack)

I would like to know why I am using vectors if they are safe.

6
  • This is a very broad discussion if you are asking about the merits and pitfalls using std::vector, arrays and pointers. Commented Dec 6, 2016 at 22:01
  • In my code I am going to use vectors always and arrays only if I found someone that used them in the old version. But I'd like to know why Commented Dec 6, 2016 at 22:03
  • std::vector is a well honed machine that has taken over most tasks previously solved with arrays. You'd want to study how std::vector is designed and why. This includes resource management (rule of 3/5) as well as algorithmic behavior. Commented Dec 6, 2016 at 22:05
  • I guess that I'll use them for now and maybe later, when I'll have more knowleadge about the topic, I'll understand better. Commented Dec 6, 2016 at 22:07
  • And the extra memory required is almost always negliglble, Three pointers instead of one (+size) or possibly none, for all the data. Commented Dec 6, 2016 at 22:07

3 Answers 3

3

The reason arrays are unsafe is because of memory leaks.

If you declare a dynamic array

int * arr = new int[size]

and you don't do delete [] arr, then the memory remains uncleared and this is known as a memory leak. It should be noted, ANY time you use the word new in C++, there must be a delete somewhere in there to free that memory. If you use malloc(), then free() should be used.

http://ptolemy.eecs.berkeley.edu/ptolemyclassic/almagest/docs/prog/html/ptlang.doc7.html

It is also very easy to go out of bounds in an array, for example inserting a value in an index larger than its size -1. With a vector, you can push_back() as many elements as you want and the vector will resize automatically. If you have an array of size 15 and you try to say arr[18] = x, Then you will get a segmentation fault. The program will compile, but will crash when it reaches a statement that puts it out of the array bounds.

In general when you have large code, arrays are used infrequently. Vectors are objectively superior in almost every way, and so using arrays becomes sort of pointless.

EDIT: As Paul McKenzie pointed out in the comments, going out of array bounds does not guarantee a segmentation fault, but rather is undefined behavior and is up to the compiler to determine what happens

Sign up to request clarification or add additional context in comments.

3 Comments

They need more space yes, but overall I should prefer vectors. I guess that I have understood where the "safety" is :) Also vectors can be implemented with a lot of useful methods; arrays are "ancient" and could be used for C retro compatibility
This is true. Vectors use more storage, but this is nebulous compared to the security/efficiency advantages that come with vectors
@ConnorSchwinghammer -- If you have an array of size 15 and you try to say arr[18] = x, Then you will get a segmentation fault -- You are not guaranteed a segmentation fault if you go out of bounds using [ ] for a vector (yes, the debug Visual C++ runtime will check, but not the release version). So you basically can suffer the same undefined behavior as using regular arrays when you go out-of-bounds. However, vector has the at() function, which guarantees that if the index is out-of-bounds, a std::out_of_range exception is thrown. So maybe you should amend your answer?
2

Let us take the case of reading numbers from a file.
We don't know how many numbers are in the file.

To declare an array to hold the numbers, we need to know the capacity or quantity, which is unknown. We could pick a number like 64. If the file has more than 64 numbers, we start overwriting the array. If the file has fewer than 64 (like 16), we are wasting memory (by not using 48 slots). What we need is to dynamically adjust the size of the container (array).

To dynamically adjust the capacity of an array, a new larger array must be created, then elements copied and the old array deleted.

The std::vector will adjust its capacity as necessary. It handles the dynamic allocation of memory for you.

Another aspect is the passing of the container to a function. With an array, you need to pass the array and the capacity. With std::vector, you only need to pass the vector. The vector object can be queried about its capacity.

Comments

-4

One Security I can see is that you can't access something in vector which is not there.

What I meant by that is , if you push_back only 4 elements and you try to access index 7 , then it will throw back an error. But in array that doesn't happen.

In short, it stops you from accessing corrupt data.

edit :

programmer has to compare the index with vector.size() to throw an error. and it doesn't happne automatically. One has to do it by himself/herself.

4 Comments

This is untrue in most circumstances.
@CaptainGiraffe , I meant like before using any index number, we can compare it with vector.size() , and we can decide whether it's out of bound or not.
This is also the case for any reasonable use of arrays.
If you want automatic, you got std::vector::at() cplusplus.com/reference/vector/vector/at "The function automatically checks whether n is within the bounds of valid elements in the vector, throwing an out_of_range exception if it is not (i.e., if n is greater than, or equal to, its size). This is in contrast with member operator[], that does not check against bounds."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.