-1

if I don't define the size of my vector the segmentation fault will occur but in this way , I mean that I define the size lower than the size I use , the segmentation fault won't occur . but why? what is the difference between them ?

#include <iostream>
#include <string>
using namespace std;
#include <vector>
int main()
{
    vector <string> a(2);
    a[0]="hello world";
    a[2]="maryam";
    cout << a[0] << a[2];
    return 0;

}
marass
  • 35
  • 4
  • 5
    You're causing undefined behavior. The behavior in this case is undefined. A segmentation fault is just one possible result of undefined behavior. Your computer could order pizza or format your disk instead. You shouldn't expect anything. – Thomas Sablik Feb 28 '21 at 12:11
  • 1
    @ThomasSablik: that's *related* but refers to an actual array rather than a vector. I'll leave it to the swarm to decide if it's an *actual* dupe. – paxdiablo Feb 28 '21 at 12:20

3 Answers3

1

Undefined behaviour (which is what you're doing when reading or writing beyond the end of a vector with operator[]) is exactly that, undefined.

It could just as easily crash for the size two case and seem to work for size zero.

Or both could format your storage devices while playing maniacal_laughter.mp3.

Undefined behaviour places no limits on the outcome, and it's something you would be well advised to steer clear of.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
1

[] operator does not have range check. [] operator is used for directly accessing a memory address based on the offset value and "base" address. From your example,

a[0], a[2]

0 and 2 are offset values, and "base" address will be the address of the array, pointed by the vector.
If you want to have range check, use:

a.at(0), a.at(2)
AlishZ
  • 19
  • 4
1

C++ has a notion of undefined behavior. Accessing a vector out-of-bounds is a typical example of undefined behavior (because vector::operator[] performs no bounds checking). Nothing meaningful can be said about the outcome of the program.

But to explain what probably happens...

A vector is a class that usually contains a pointer to a heap-allocated array and its size (the "capacity").

An empty vector has a null pointer value. Dereferencing a null pointer often immediately leads to a segfault because there's no virtual memory region allocated at address 0.

On the other hand, a vector of capacity 2 points to an array of size 2. Writing past it is often possible, you will simply overwrite heap memory that happens to reside immediately after that array. This is called a heap buffer overflow. In a simple program it may appear to work fine. But in a larger program nothing good will happen somewhere further down the code.

rustyx
  • 80,671
  • 25
  • 200
  • 267