On Sun, 12 Nov 2023, 00:02 Navin P via Gcc-help, <gcc-help@xxxxxxxxxxx> wrote: > Hi, > > Why doesn't sanitizer catch this ? The value ptr is a valid address but it > did a buffer overflow into another object a3 and then it is a valid > address. This is from production code where a ptr whose base was different > array address overflows into another array and becomes a valid address. > This is not caught by address sanitizer. > > - How do you detect this and fix this ? Are there any alternative > datastructures in C or C++ that prevent these kind of overruns > Use std::vector instead of allocating arrays using calloc. Or allocate arrays yourself and then use std::span to access into them. Performing pointer arithmetic and indexing via pointers is simply not going to be safe, either get it right, or stop doing it. Both vector and span have checks that can be enabled to diagnose when you overflow. Raw pointers don't. Please don't increase the cookie or red zone size between arrays. Again > sizes more than the cookie or redzone between arrays or objects can be > overrun > > > > navin@Navin-acer-5740:~/cpp$ gcc -fsanitize=address sanitizer.c > navin@Navin-acer-5740:~/cpp$ ./a.out > a1=(0x614000000040-0x6140000001d0) a2=(0x614000000240-0x6140000003d0) > a3=(0x614000000440-0x6140000005d0) > value=0, ptr=0x614000000498 > ptr lies in the array a3 > navin@Navin-acer-5740:~/cpp$ cat sanitizer.c > #include<stdlib.h> > #include<stdio.h> > int main(){ > int *a1=calloc(100,sizeof(int)); > int *a2=calloc(100,sizeof(int)); > int *a3=calloc(100,sizeof(int)); > > printf("a1=(%p-%p) a2=(%p-%p) a3=(%p-%p)\n",a1,a1+100,a2,a2+100,a3,a3+100); > int *ptr=a2; > ptr+=150; > printf("value=%d, ptr=%p\n",*ptr,ptr); > if(a3<=ptr && ptr<=a3+100) printf("ptr lies in the array a3\n"); > > free(a1); > free(a2); > free(a3); > } > navin@Navin-acer-5740:~/cpp$ > > > Regards, > Navin >