Jump to content
357mag

Program works fine but why?

Recommended Posts

Just one question about the way this program is working.  I make a constant and initialize it to 10. I use that to make the size of the array called name1. What I don't understand though is if I run the program and enter in a long name that is longer than 10 characters, C++ still allows me to do it and the program works just fine.

 

I was expecting an error message saying something about 'out of bounds error".

 

I don't get why C++ is allowing me to enter in a name that is longer than the size of the array:

 

#include<iostream>
#include<cstring>
using namespace std;

int main()
{
    const int SIZE = 10;
    char name1[SIZE];
    char name2[SIZE] = "C++owboy";

    cout << "Howdy! I'm " << name2 << "!";
    cout << " What's your name?" << endl;
    cin >> name1;
    cout << "Well, " << name1 << " your name has ";
    cout << strlen(name1) << " letters" << endl;
    cout << "Your initial is " << name1[0] << endl;
    name2[3] = '\0';
    cout << "Here are the first three characters of my name: ";
    cout << name2 << endl << endl;

    system("pause");
    return 0;

 

Share this post


Link to post

None of the operations you are doing perform any bounds checking. They don't even know the size of your buffers. Your code exhibits undefined behavior if your input overflows the buffers. 

 

To avoid this, use std::cin.get() or std::cin.getline(), which allow you to specify the buffer sizes.

 

Or better, just use std::string instead of char[]. 

Edited by Remy Lebeau

Share this post


Link to post

You might want to start with a beginners book to learn C++ that will take you through all of this learning. And you definitely don't want to be using character arrays when strings exist. 

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×