Back to TILs

C++ buffer overflow

Date: 2023-02-16Last modified: 2024-02-26

Table of contents

  char var1[4]; // stack
  char var2[4]; // stack
  char var3[4]; // stack

  std::stringstream input( "1234567890\nABCDEFG\nRSTUVX" );

  fmt::print( "var1 address: {}\n", static_cast<void *>( var1 ) );
  fmt::print( "var2 address: {}\n", static_cast<void *>( var2 ) );
  fmt::print( "var3 address: {}\n", static_cast<void *>( var3 ) );
  fmt::print( "var1: '{}'  var2: '{}'  var3: '{}'\n", var1, var2, var3 );

  fmt::print("Input -> var2\n");
  input.getline( var2, '\n' );
  fmt::print( "var1: '{}'  var2: '{}'  var3: '{}'\n", var1, var2, var3 );

  fmt::print("Input -> var1\n");
  input.getline( var1, '\n' );
  fmt::print( "var1: '{}'  var2: '{}'  var3: '{}'\n", var1, var2, var3 );

Possible output

var1 address: 0x7ffee672927c
var2 address: 0x7ffee6729278
var3 address: 0x7ffee6729274
var1: ''  var2: ''  var3: ''
Input -> var2
var1: '56789'  var2: '123456789'  var3: ''
Input -> var1
var1: ''  var2: '1234'  var3: ''

References