This malloc shouldn't work

后端 未结 5 1789
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-23 17:06

Here is my code.

 int     main()
  {
  char *s;
  int i = 0;

  printf(\"%lu \\n\", sizeof(s));

  s = malloc(sizeof(char) * 2);

  printf(\"%lu \\n\", sizeof(s         


        
5条回答
  •  清歌不尽
    2021-01-23 17:48

    As others have said, its hit or miss whether the code will cause a runtime error in production since bounds checking is not built into C++ (unlike languages Java or C#). The code will cause an error under a memory checker.

    You probably know Valgrind, so that's an exercise left to the reader. Here's the same under Clang's Address Sanitizer (I added a printf("malloc: %p \n", s);):

    $ ./t.exe | /usr/local/bin/asan_symbolize.py 
    malloc: 0x60200000b3b0 
    =================================================================
    ==98557==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60200000b3b2 at pc 0x1065c4b5b bp 0x7fff5963b810 sp 0x7fff5963b808
    WRITE of size 1 at 0x60200000b3b2 thread T0
        #0 0x1065c4b5a (/Users/jwalton/./t.exe+0x100000b5a)
        #1 0x7fff870e27e0 (/usr/lib/system/libdyld.dylib+0x27e0)
        #2 0x0
    0x60200000b3b2 is located 0 bytes to the right of 2-byte region [0x60200000b3b0,0x60200000b3b2)
    allocated by thread T0 here:
        #0 0x1065d8cd5 (/usr/local/lib/clang/3.3/lib/darwin//libclang_rt.asan_osx_dynamic.dylib+0xfcd5)
        #1 0x1065c4971 (/Users/jwalton/./t.exe+0x100000971)
        #2 0x7fff870e27e0 (/usr/lib/system/libdyld.dylib+0x27e0)
        #3 0x0
    Shadow bytes around the buggy address:
      0x1c0400001620: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
      0x1c0400001630: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
      0x1c0400001640: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
      0x1c0400001650: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
      0x1c0400001660: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
    =>0x1c0400001670: fa fa fa fa fa fa[02]fa fa fa 00 00 fa fa fd fa
      0x1c0400001680: fa fa fd fa fa fa 00 00 fa fa fd fa fa fa fd fa
      0x1c0400001690: fa fa 00 00 fa fa 00 00 fa fa fd fa fa fa fd fa
      0x1c04000016a0: fa fa fd fa fa fa fd fa fa fa fd fa fa fa fd fa
      0x1c04000016b0: fa fa 00 00 fa fa fd fa fa fa fd fa fa fa 00 00
      0x1c04000016c0: fa fa 00 00 fa fa fd fa fa fa fd fa fa fa 00 00
    Shadow byte legend (one shadow byte represents 8 application bytes):
      Addressable:           00
      Partially addressable: 01 02 03 04 05 06 07 
      Heap left redzone:     fa
      Heap right redzone:    fb
      Freed heap region:     fd
      Stack left redzone:    f1
      Stack mid redzone:     f2
      Stack right redzone:   f3
      Stack partial redzone: f4
      Stack after return:    f5
      Stack use after scope: f8
      Global redzone:        f9
      Global init order:     f6
      Poisoned by user:      f7
      ASan internal:         fe
    ==98557==ABORTING
    

提交回复
热议问题