| 1 |
// Copyright (C) 2020-2025 Free Software Foundation, Inc. |
| 2 |
// |
| 3 |
// This file is part of the GNU ISO C++ Library. This library is free |
| 4 |
// software; you can redistribute it and/or modify it under the |
| 5 |
// terms of the GNU General Public License as published by the |
| 6 |
// Free Software Foundation; either version 3, or (at your option) |
| 7 |
// any later version. |
| 8 |
|
| 9 |
// This library is distributed in the hope that it will be useful, |
| 10 |
// but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 |
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 |
// GNU General Public License for more details. |
| 13 |
|
| 14 |
// You should have received a copy of the GNU General Public License along |
| 15 |
// with this library; see the file COPYING3. If not see |
| 16 |
// <http://www.gnu.org/licenses/>. |
| 17 |
|
| 18 |
// { dg-options "-O2" } |
| 19 |
// { dg-do run } |
| 20 |
|
| 21 |
// This test checks that operator>> will avoid a buffer overflow when |
| 22 |
// reading into a buffer with a size that is known at compile time. |
| 23 |
|
| 24 |
// Since C++20 this is guaranteed (see LWG 2499), for previous standards |
| 25 |
// checking the buffer size is an extension and depends on optimisation. |
| 26 |
|
| 27 |
#include <sstream> |
| 28 |
#include <testsuite_hooks.h> |
| 29 |
|
| 30 |
void |
| 31 |
test01() |
| 32 |
{ |
| 33 |
std::istringstream in("foolishly"); |
| 34 |
char pc[5]; |
| 35 |
in >> pc; |
| 36 |
VERIFY( in.good() ); |
| 37 |
VERIFY( std::string(pc) == "fool" ); |
| 38 |
|
| 39 |
#if __cplusplus <= 201703L |
| 40 |
char* p = pc + 1; |
| 41 |
in >> p; |
| 42 |
VERIFY( in.good() ); |
| 43 |
VERIFY( std::string(pc) == "fish" ); |
| 44 |
|
| 45 |
p = pc + 4; |
| 46 |
*p = '#'; |
| 47 |
in >> p; |
| 48 |
VERIFY( in.fail() ); // if no characters are extracted, failbit is set |
| 49 |
VERIFY( *p == '\0' ); |
| 50 |
#endif |
| 51 |
} |
| 52 |
|
| 53 |
void |
| 54 |
test02() |
| 55 |
{ |
| 56 |
std::istringstream in("foolish"); |
| 57 |
signed char sc[5]; |
| 58 |
in >> sc; |
| 59 |
VERIFY( in.good() ); |
| 60 |
VERIFY( std::string((const char*)sc) == "fool" ); |
| 61 |
} |
| 62 |
|
| 63 |
void |
| 64 |
test03() |
| 65 |
{ |
| 66 |
std::istringstream in("foolish"); |
| 67 |
unsigned char uc[5]; |
| 68 |
in >> uc; |
| 69 |
VERIFY( in.good() ); |
| 70 |
VERIFY( std::string((const char*)uc) == "fool" ); |
| 71 |
} |
| 72 |
|
| 73 |
int |
| 74 |
main() |
| 75 |
{ |
| 76 |
test01(); |
| 77 |
test02(); |
| 78 |
test03(); |
| 79 |
} |