Why doesn’t segmentation fault occur in std::string array? [duplicate]

  address-sanitizer, c++, segmentation-fault

This is my code:

#include <iostream>
#include <string>

int main(void)
{
    std::string str[10];
    std::cout << str[100] << std::endl;

    int intval[10];
    std::cout << intval[100] << std::endl;
    
    return (0);
}

Compiling with -g3 -fsanitize=address and executing results in the following error:

==1344447==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7fff23e85690 at pc 0x55d0c16794b7 bp 0x7fff23e854b0 sp 0x7fff23e854a0
READ of size 4 at 0x7fff23e85690 thread T0
    #0 0x55d0c16794b6 in main /goinfre/segfault.cpp:10
    #1 0x7fb8e8e7b0b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
    #2 0x55d0c16792ad in _start (/goinfre/a.out+0x12ad)

Address 0x7fff23e85690 is located in stack of thread T0 at offset 448 in frame
    #0 0x55d0c1679378 in main /goinfre/segfault.cpp:5

  This frame has 2 object(s):
    [48, 88) 'intval' (line 9)
    [128, 448) 'str' (line 6) <== Memory access at offset 448 overflows this variable
HINT: this may be a false positive if your program uses some custom stack unwind mechanism, swapcontext or vfork
      (longjmp and C++ exceptions *are* supported)
SUMMARY: AddressSanitizer: stack-buffer-overflow /home/seyu/Documents/goinfre/segfault.cpp:10 in main
Shadow bytes around the buggy address:
  0x1000647c8a80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x1000647c8a90: 00 00 00 00 00 00 00 00 00 00 f1 f1 f1 f1 f1 f1
  0x1000647c8aa0: 00 00 00 00 00 f2 f2 f2 f2 f2 00 00 00 00 00 00
  0x1000647c8ab0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x1000647c8ac0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x1000647c8ad0: 00 00[f3]f3 f3 f3 f3 f3 f3 f3 00 00 00 00 00 00
  0x1000647c8ae0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x1000647c8af0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x1000647c8b00: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x1000647c8b10: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x1000647c8b20: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Shadow byte legend (one shadow byte represents 8 application bytes):
  ...
==1344447==ABORTING

I expected SEGFAULT on line 7 but SEGFAULT on line 10 occured. After delete line 10, it works without error.

Why?? Isn’t fsanitize=address perfect? Can’t I trust fsanitize=address?

Why is line 7 SEGFAULT safe??

Source: Windows Questions C++

LEAVE A COMMENT