'addressSanitizer: heap-buffer-overflow on address
I am at the very beginning of learning C.
I am trying to write a function to open a file, read a BUFFER_SIZE
, store the content in an array, then track the character '\n'
(because I want to get each line of the input).
when I set the BUFFER_SIZE
very large, I can get the first line. when I set the BUFFER_SIZE
reasonably small (say, 42) which is not yet the end of the first line , it prints out some weird symbol at the end, but I guess it is some bug in my own code.
however, when I set the BUFFER_SIZE
very small, say = 10, and i use the -fsanitizer=address
to check for memory leak. it throws a monster of error:
==90673==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x6020000000fb at pc 0x000108868a95 bp 0x7fff573979a0 sp 0x7fff57397998
READ of size 1 at 0x6020000000fb thread T0
If anyone can explain me in a general sense:
what is fsanitizer=address flag?
what is heap-buffer-overflow?
what is address and thread? what is the flag to see the thread in colors on screen?
and why it says 'read of size 1 at address.." ?
i would really appreciate <3
Solution 1:[1]
what is fsanitizer=address flag?
Usually C compiler doesn't add boundaries check for memory access. Sometimes due to code error, there is read or write from outside the buffer, such an error is usually hard to detect. Using this flag the compiler add some boundaries check, to ensure you won't use a buffer to reach outside of its allocation.
what is heap-buffer-overflow?
use an array to reach after its allocation,
char* x = malloc(10);
char n=x[11]; //heap-buffer-overflow
(underflow is to reach before its allocation)
char* x = malloc(10);
char n=x[-11]; //heap-buffer-underflow
what is address and thread?
Address is position in memory, thread is part of process running sequence of code.
and why it says 'read of size 1 at address.." ?
It means you read single byte form the given address.
I think your problem is that you allocate the BUFFER_SIZE
for the buffer and read the same BUFFER_SIZE
into it. The correct approach is to always declare at least one more byte than you read.
like this:
char* buff = malloc(BUFFER_SIZE+1);//notice to +1
fread(buff,1,BUFFER_SIZE,fp);
Solution 2:[2]
In simple words it is segmentation fault with the variable created using new keyword as all that goes into heap area of memory.
Explanation - you are trying to access such an address for which you haven't declared your variable, to find all such errors revisit all your conditions and check if you are accessing something out of bounds or not.
Solution 3:[3]
This can also be rectified by making fast input output by:-
//For FAST I/O
**ios_base::sync_with_stdio(false);
cin.tie(NULL);**
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | displayName |
Solution 2 | |
Solution 3 | Hari Prakash |