runtime error: store to address 0x6020000000b8 、、、 和AddressSanitizer: heap-buffer-overflow on address 、、、

这两个问题为力扣刷题malloc分配内存空间的常见错误。

问题1:

Line 32: Char 17: runtime error: store to address 0x6020000000b8 with insufficient space for an object of type 'int' [solution.c]
0x6020000000b8: note: pointer points here
 02 00 00 00  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  00 00 00 00

问题代码:

  int *a = (int *)malloc(sizeof(a));

解决方案:将sizeof(a)改为sizeof(int)*nums
nums为数组大小

 int *a = (int *)malloc(sizeof(int)*nums);

问题2:

=================================================================
==42==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x6020000001d4 at pc 0x7f0a099c0f2d bp 0x7ffdbdb287e0 sp 0x7ffdbdb27f88
WRITE of size 8 at 0x6020000001d4 thread T0
    #0 0x7f0a099c0f2c  (/lib/x86_64-linux-gnu/libasan.so.5+0x67f2c)
    #3 0x7f0a08e210b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
0x6020000001d4 is located 0 bytes to the right of 4-byte region [0x6020000001d0,0x6020000001d4)
allocated by thread T0 here:
    #0 0x7f0a09a66bc8 in malloc (/lib/x86_64-linux-gnu/libasan.so.5+0x10dbc8)
    #3 0x7f0a08e210b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
SUMMARY: AddressSanitizer: heap-buffer-overflow (/lib/x86_64-linux-gnu/libasan.so.5+0x67f2c) 
Shadow bytes around the buggy address:
  0x0c047fff7fe0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0c047fff7ff0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0c047fff8000: fa fa fd fd fa fa 00 00 fa fa 00 00 fa fa 00 00
  0x0c047fff8010: fa fa 00 00 fa fa 00 00 fa fa 05 fa fa fa fd fa
  0x0c047fff8020: fa fa 00 00 fa fa 00 00 fa fa 00 fa fa fa 06 fa
=>0x0c047fff8030: fa fa fd fa fa fa 00 00 fa fa[04]fa fa fa fa fa
  0x0c047fff8040: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c047fff8050: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c047fff8060: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c047fff8070: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c047fff8080: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
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
  Freed heap region:       fd
  Stack left redzone:      f1
  Stack mid redzone:       f2
  Stack right redzone:     f3
  Stack after return:      f5
  Stack use after scope:   f8
  Global redzone:          f9
  Global init order:       f6
  Poisoned by user:        f7
  Container overflow:      fc
  Array cookie:            ac
  Intra object redzone:    bb
  ASan internal:           fe
  Left alloca redzone:     ca
  Right alloca redzone:    cb
  Shadow gap:              cc
==42==ABORTING

问题代码:

   int *a = (int *)malloc(sizeof(int)*nums);

解决方案:数组大小定义过小,导致访问越界,适当增加数组的大小即可。

   int *a = (int *)malloc(sizeof(int)*(nums+1);
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐