看似正确的代码:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
static int indexes[1000] = {0};
int i = 0, j = 0;
for (i = 0; i < numsSize - 1; i++) {
for (j = i + 1; j < numsSize; j++) {
if (nums[i] + nums[j] == target) {
indexes[0] = i;
indexes[1] = j;
return indexes;
}
}
}
return indexes;
}
然鹅:
=================================================================
==29==ERROR: AddressSanitizer: global-buffer-overflow on address 0x00000043cf80 at pc 0x0000004050fa bp 0x7ffd6e50a120 sp 0x7ffd6e50a110
READ of size 4 at 0x00000043cf80 thread T0
#2 0x7fbe2223982f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)
0x00000043cf80 is located 32 bytes to the left of global variable 'tokens' defined in '__DeserializerHelper__.inl:44:20' (0x43cfa0) of size 100000000
0x00000043cf80 is located 0 bytes to the right of global variable 'indexes' defined in 'prog.c:5:16' (0x43bfe0) of size 4000
Shadow bytes around the buggy address:
0x00008007f9a0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x00008007f9b0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x00008007f9c0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x00008007f9d0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x00008007f9e0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x00008007f9f0:[f9]f9 f9 f9 00 00 00 00 00 00 00 00 00 00 00 00
0x00008007fa00: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x00008007fa10: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x00008007fa20: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x00008007fa30: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x00008007fa40: 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):
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
==29==ABORTING
百思不得其解,怎么就越界了???