换一个好点的编译器,可以帮你检查出更多的问题
$ cat main.c
#include <stdio.h>
#include <malloc.h>
#define N 9
int main()
{
int **p=(int**)malloc(sizeof(int)*N);
for(int i=0;i<N;i++)
{
p[i]=(int*)malloc(sizeof(int)*N);
}
int m=1;
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
(*(p+i))[j]=m++;
}
}
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
printf("%4d ",(*(p+i))[j]);
}
printf("\n");
}
for(int i=0;i<N;i++)
{
free(*(p+i));
}
free(p);
return 0;
}
$ gcc-debug -o main main.c
$ ./main
=================================================================
==2144349==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x604000000030 at pc 0x561b0dd312e1 bp 0x7ffe4dc688f0 sp 0x7ffe4dc688e0
WRITE of size 8 at 0x604000000030 thread T0
#0 0x561b0dd312e0 in main /tmp/main.c:10
#1 0x7f34ce3b130f in __libc_start_call_main (/usr/lib/libc.so.6+0x2d30f)
#2 0x7f34ce3b13c0 in __libc_start_main@GLIBC_2.2.5 (/usr/lib/libc.so.6+0x2d3c0)
#3 0x561b0dd31144 in _start (/tmp/main+0x2144)
0x604000000034 is located 0 bytes to the right of 36-byte region [0x604000000010,0x604000000034)
allocated by thread T0 here:
#0 0x7f34cefbadd9 in __interceptor_malloc /usr/src/debug/gcc/libsanitizer/asan/asan_malloc_linux.cpp:145
#1 0x561b0dd3122f in main /tmp/main.c:7
#2 0x7f34ce3b130f in __libc_start_call_main (/usr/lib/libc.so.6+0x2d30f)
SUMMARY: AddressSanitizer: heap-buffer-overflow /tmp/main.c:10 in main
Shadow bytes around the buggy address:
0x0c087fff7fb0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c087fff7fc0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c087fff7fd0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c087fff7fe0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c087fff7ff0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x0c087fff8000: fa fa 00 00 00 00[04]fa fa fa 00 00 00 00 04 fa
0x0c087fff8010: fa fa 00 00 00 00 04 fa fa fa 00 00 00 00 04 fa
0x0c087fff8020: fa fa 00 00 00 00 04 fa fa fa 00 00 00 00 04 fa
0x0c087fff8030: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c087fff8040: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c087fff8050: 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
==2144349==ABORTING
$
|