LinuxQuestions.org
Download your favorite Linux distribution at LQ ISO.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 01-03-2016, 05:16 PM   #1
killingthemonkey
Member
 
Registered: Mar 2011
Location: Winston-Salem, NC
Distribution: Fedora, CentOS, Linux Mint
Posts: 259

Rep: Reputation: 24
C++ - char Array Holding More Letters It Should


I've set my array to a length of fifteen.

When I enter more than fifteen letters, it takes it without complaint. The strlen() function returns the correct number of letters. This works out to at least forty letters. I entered 120 letters and it still worked, but it threw a segmentation fault.

Any idea as to why?

My code is straight from C++ Primer Plus.

It's 'Listing 4.2' in chapter 4.

Code:
// strings.cpp -- storing strings in an array
#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    const int ArSize = 15;
    char name1[ArSize];                         // empty array
    char name2[ArSize] = "C++owboy";            // initialized array

    cout << "Howdy! My name is " << name2;
    cout << "! What's your name?\n";
    cin >> name1;
    cout << "Well, " << name1 << ", your name has ";
    cout << strlen(name1) << " letters, and is stored\n";
    cout << "in an array of " << sizeof(name1) << " bytes.\n";
    cout << "Your initial is " << name1[0] << ".\n";
    name2[3] = '\0';                            // set to null character
    cout << "Here are the first three letters of my name: ";
    cout << name2 << endl;
    return 0;    
}
Results from entering 120 characters:
Code:
[dknapp@opensourcegort C++]$ ./a.out
Howdy! My name is C++owboy! What's your name?
kkklkljjkkjkjjjkkjknmkjmkjnmkkjjhjhggfdfhghhtdrdgmhgjyftdrsytfkjnlkjoiuyfkjbnkjlihyiuyfjblknihiuguyfvkjblkhouiguyfkjbljh
Well, kkklkljjkkjkjjjkkjknmkjmkjnmkkjjhjhggfdfhghhtdrdgmhgjyftdrsytfkjnlkjoiuyfkjbnkjlihyiuyfjblknihiuguyfvkjblkhouiguyfkjbljh, your name has 120 letters, and is stored
in an array of 15 bytes.
Your initial is k.
Here are the first three letters of my name: C++
Segmentation fault (core dumped)
I'm on a 64bit machine with Fedora 23. I'm using the C++ implementation that's installed by default.

Last edited by killingthemonkey; 01-03-2016 at 05:19 PM.
 
Old 01-03-2016, 05:49 PM   #2
astrogeek
Moderator
 
Registered: Oct 2008
Distribution: Slackware [64]-X.{0|1|2|37|-current} ::12<=X<=15, FreeBSD_12{.0|.1}
Posts: 6,269
Blog Entries: 24

Rep: Reputation: 4196Reputation: 4196Reputation: 4196Reputation: 4196Reputation: 4196Reputation: 4196Reputation: 4196Reputation: 4196Reputation: 4196Reputation: 4196Reputation: 4196
In C and C++ it is up to the programmer to assure that the program never writes past the end of the array.

If you DO ask it to write past the end of the array it will do as it has been asked and simply overwrite whatever is there. The fact that it results in a segmentation fault at 120 characters in your specific case is not of any great significance - it is just corrupted memory that causes a crash.

Your code must be written in such a way that it prevents writing past the end of the array.
 
Old 01-03-2016, 07:59 PM   #3
killingthemonkey
Member
 
Registered: Mar 2011
Location: Winston-Salem, NC
Distribution: Fedora, CentOS, Linux Mint
Posts: 259

Original Poster
Rep: Reputation: 24
Thank you, astrogeek.

So, I'm thinking cin.getline() would be better than a bare cin.



Quote:
Originally Posted by astrogeek View Post
In C and C++ it is up to the programmer to assure that the program never writes past the end of the array.

If you DO ask it to write past the end of the array it will do as it has been asked and simply overwrite whatever is there. The fact that it results in a segmentation fault at 120 characters in your specific case is not of any great significance - it is just corrupted memory that causes a crash.

Your code must be written in such a way that it prevents writing past the end of the array.
 
Old 01-03-2016, 08:13 PM   #4
sundialsvcs
LQ Guru
 
Registered: Feb 2004
Location: SE Tennessee, USA
Distribution: Gentoo, LFS
Posts: 10,667
Blog Entries: 4

Rep: Reputation: 3945Reputation: 3945Reputation: 3945Reputation: 3945Reputation: 3945Reputation: 3945Reputation: 3945Reputation: 3945Reputation: 3945Reputation: 3945Reputation: 3945
C++ provides a very fine string type. You should be using that.
 
Old 01-03-2016, 11:47 PM   #5
NevemTeve
Senior Member
 
Registered: Oct 2011
Location: Budapest
Distribution: Debian/GNU/Linux, AIX
Posts: 4,869
Blog Entries: 1

Rep: Reputation: 1870Reputation: 1870Reputation: 1870Reputation: 1870Reputation: 1870Reputation: 1870Reputation: 1870Reputation: 1870Reputation: 1870Reputation: 1870Reputation: 1870
The safe way to handle user-input is fgets+sscanf or fgets+strtok_r+sscanf
 
Old 01-04-2016, 11:01 AM   #6
killingthemonkey
Member
 
Registered: Mar 2011
Location: Winston-Salem, NC
Distribution: Fedora, CentOS, Linux Mint
Posts: 259

Original Poster
Rep: Reputation: 24
Actually, very next section of the chapter.

Quote:
Originally Posted by sundialsvcs View Post
C++ provides a very fine string type. You should be using that.
 
Old 01-04-2016, 05:02 PM   #7
sundialsvcs
LQ Guru
 
Registered: Feb 2004
Location: SE Tennessee, USA
Distribution: Gentoo, LFS
Posts: 10,667
Blog Entries: 4

Rep: Reputation: 3945Reputation: 3945Reputation: 3945Reputation: 3945Reputation: 3945Reputation: 3945Reputation: 3945Reputation: 3945Reputation: 3945Reputation: 3945Reputation: 3945
When you specify "an array," without using any sort of container-class, then what you get is a fixed-size block of storage. It is entirely your responsibility to see to it that your code never accesses any location outside of that block. (C/C++ does not check the value of array indexes!)

On the other hand, when you simply use the string type, the implementation of that type provides you with a variable-sized storage area, which grows or contracts as needed and which conceals from you (yay!) all of the associated "messy details." (Furthermore, the type "knows" that it exists to manage ... "strings.")

Whenever possible, therefore: (a) "use C++ ... that's what it's there for." And, (b) use the "smart" classes and data-types which C++ provides, such as strings and various forms of "containers."

When you do this, you silently leverage the "smart work" of "many clever (other!) people," who tackled many otherwise-thorny problems on your behalf, specifically so that you don't have to. The resulting code is extremely efficient, and generally backwards-compatible with "C."

(Obviously, there are certain contexts, such as "writing kernel code," where C++ cannot be used.)

"Do not do a thing already done." "Do not ride the pony bareback when you have equally-convenient access to a nice saddle."
 
Old 01-05-2016, 09:50 AM   #8
killingthemonkey
Member
 
Registered: Mar 2011
Location: Winston-Salem, NC
Distribution: Fedora, CentOS, Linux Mint
Posts: 259

Original Poster
Rep: Reputation: 24
Two things.

One, I can possibly conceive of a world where I might actually write kernel code, a long, long time ago, in a galaxy far, far away.

Two, I am absolutely willing to stand on the shoulders of giants. At the moment, I'm still learning who the giants are and where they take lunch.

Quote:
Originally Posted by sundialsvcs View Post

(Obviously, there are certain contexts, such as "writing kernel code," where C++ cannot be used.)

"Do not do a thing already done." "Do not ride the pony bareback when you have equally-convenient access to a nice saddle."
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
Returning char pointer from function which has array of char pointer srinietrx Programming 3 10-30-2015 03:55 AM
How do I point a char pointer to a part of another char array? trist007 Programming 8 11-06-2010 07:56 PM
scanf reading newline into char array while reading 1 char at a time austinium Programming 6 09-26-2010 11:27 PM
How to convert short array to char array? bvkim Programming 4 06-08-2010 09:26 AM
C++ help Dynamic array and "invalid conversion from ‘char’ to ‘char*’" heathf Programming 2 04-25-2009 09:20 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 07:24 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration