Back to TILs

C++ buffer overflow

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

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: 0x7ffead273f24
var2 address: 0x7ffead273f28
var3 address: 0x7ffead273f2c
var1: ''  var2: '�C'��'  var3: '�'
Input -> var2
var1: ''  var2: '123456789'  var3: '56789'
Input -> var1
var1: ''  var2: '123456789'  var3: '56789'

References