0

I am doing some tests and got around this:

#include <stdio.h>

#include <vector>
#include <string>

class Person{
public:
    std::string name;

    Person(const char *name):
        name(name){
            printf("c-tor for %s\n", name);
        };

    void print(){
        printf(">> %s\n", name.c_str());
    };
};

int main(){
    std::vector<Person> v;

    v.push_back("Ivan");
    v.push_back("Stoyan");
    v.push_back("Dragan");

    v[10].print();
}

If I do it with std::cout, it crashes. However if I do it with printf, it prints:

c-tor for Ivan
c-tor for Stoyan
c-tor for Dragan
>> (null)

Is this working "correctly" just by chance and coincidence?

Portable programs should never call this function with an argument n that is out of range, since this causes undefined behavior.

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
Nick
  • 9,962
  • 4
  • 42
  • 80
  • 1
    Undefined behavior is undefined. So asking for seemingly working stuff is useless. – πάντα ῥεῖ Jul 14 '15 at 09:18
  • It's just undefined. Behavior depends on compiler you use. – kosmo16 Jul 14 '15 at 09:20
  • It is not working "correctly". Since it is undefined behaviour (as you quoted yourself), there is no "correct" way. – Verena Haunschmid Jul 14 '15 at 09:22
  • Undefined behavior means anything can happen. It can even work as expected, which (ironically) can sometimes be very frustrating: you may first think it works and much later your program crashes or behaves very strange, and you don't find the source of the problem... To put it in a nutshell, avoid undefined behavior by all means, even if it seems to work at first. – leemes Jul 14 '15 at 09:23

1 Answers1

3

Is this working "correctly" just by chance and coincidence?

Yes.

You have given the reason yourself with the quote

Portable programs should never call this function with an argument n that is out of range, since this causes undefined behavior.

Accessing v[10] when v.size() is less than 11 is undefined behavior and thus your program may crash or give unexpected (sometimes seeming correct) output.

cout may print std::string in a different way than accessing std::string::c_str and thus cout and printf may give different results.

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100