I get a heap-buffer-overflow error when i compile th code:
char * reverseWords(char * s){
int n = strlen(s);
char *res = malloc(n + 1);
strcpy(res,s);
char temp[100];
int i = 0;
int j = 0;
for (i = 0; i < n; i++){
for (j = 0; j < n; j++, i++){
if (res[i] == ' ') break;
temp[j] = res[i];
}
while (j > 0){
j--;
res[i - j - 1] = temp[j];
}
}
return res;
}
I need reverse each words in string. I think the error is caused in this line (if (res[i] == ' ') break;) My idea is to find end of each words and reverse him. When I compile I get this error:
==30==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60300000005c at pc 0x5620553333a3 bp 0x7ffde02da850 sp 0x7ffde02da840
READ of size 1 at 0x60300000005c thread T0
#2 0x7f359ea9c0b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
0x60300000005c is located 0 bytes to the right of 28-byte region [0x603000000040,0x60300000005c)
allocated by thread T0 here:
#0 0x7f359f6e1bc8 in malloc (/lib/x86_64-linux-gnu/libasan.so.5+0x10dbc8)
#3 0x7f359ea9c0b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
Shadow bytes around the buggy address:
0x0c067fff7fb0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c067fff7fc0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c067fff7fd0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c067fff7fe0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c067fff7ff0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x0c067fff8000: fa fa 00 00 00 04 fa fa 00 00 00[04]fa fa fa fa
0x0c067fff8010: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c067fff8020: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c067fff8030: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c067fff8040: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c067fff8050: 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
==30==ABORTING