Is returned string null-terminated from getline()?
Asked Answered
J

2

7

One thing I'm not pretty sure after googling for a while, is the returned string of getline(). Hope to get it confirmed here.

std::getline

This global version returns a std::string so it's not necessarily null-terminated. Some compilers may append a '\0' while the others won't.

std::istream::getline

This function returns a c-style string so it's guaranteed that the string is null-terminated.

Is that right?

Jerrine answered 23/11, 2012 at 1:0 Comment(2)
null terminated doesn't mean anything for std::string. A string object stores the length and the pointer to the first byte of the string, and that is it. What you are guaranteed however is that when you call c_str, you get a null terminated array of characters.Osmund
C++11 guarantees the internal representation of std::string's data is null-terminated.Hammerskjold
A
5

Null termination is a concept that is applicable only to C strings; it does not apply to objects of std::string - they let you find the size by calling size(), and do not require null termination. However, strings returned from std::string's c_str() function are null terminated, regardless of where the data for the string came from.

C++11 standard describes the prerequisites of the operator [pos] in the section 21.4.5.2:

Returns: *(begin() + pos) if pos < size(). Otherwise, returns a reference to an object of type charT with value charT(), where modifying the object leads to undefined behavior.

Note the pos < size(), as opposed to pos <= size(): the standard explicitly allows std::string objects not to have null termination.

Anthony answered 23/11, 2012 at 1:10 Comment(6)
Does C++11 enforce that internal data of std::string is null-terminated, like GMan said?Jerrine
@EricZ Only as far as you can tell using the externally visible APIs: specifically, it guarantees that data() and c_str() will return a pointer to a null-terminated sequence of characters. There, in section 21.4.7.1.1 it says that the valid range for elements returned by data() and c_str() is [0..size()], inclusive, implying that the sequence is null-terminated.Anthony
@EricZ: If you take &str[0], you get a null-terminated buffer. It's implied by other clauses, and is an intentional change in C++11.Hammerskjold
@Hammerskjold Very interesting... I don't have the official standard, only the latest draft. It sounds like there's an inconsistency among different places in the standard when it comes to element at [size()].Anthony
@dasblinkenlight: See 1 and 2.Hammerskjold
@Hammerskjold This is very interesting - your #1 link quotes from the same section 21.4.5.2, but it has a <= instead of <.Anthony
C
0

The ending null character that signals the end of a c-string is automatically appended to s after the data extracted.

Columbary answered 23/11, 2012 at 1:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.