1

I have this code

int main()
{

  char x1[4]="abc";
  char in_buffer[2]="a";
  memcpy(in_buffer,x1,strlen(x1));
  printf("%s\n",in_buffer);
  //realoc_me(x1,in_buffer)

  return 0;
}

in above code as u can see char in_buffer[2]="a"; is 2 byte in size filled with string literal or string a\0

I ran it with gcc -Wall -Wextra nothing printed and then I did valdrind with -s and without -s still nothing printed. why this line NOT cause any error memcpy(in_buffer,x1,strlen(x1)); this line strlen(x1) returns size_t 3. writing three byte to array size of 2. I dont get it. Am i missing anything big here?

valgrind ./a.out output

==8916== Memcheck, a memory error detector
==8916== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==8916== Using Valgrind-3.17.0 and LibVEX; rerun with -h for copyright info
==8916== Command: ./a.out
==8916== 
abcbc
==8916== 
==8916== HEAP SUMMARY:
==8916==     in use at exit: 0 bytes in 0 blocks
==8916==   total heap usage: 1 allocs, 1 frees, 1,024 bytes allocated
==8916== 
==8916== All heap blocks were freed -- no leaks are possible
==8916== 
==8916== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

valgrind -s ./a.out output

==8910== Memcheck, a memory error detector
==8910== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==8910== Using Valgrind-3.17.0 and LibVEX; rerun with -h for copyright info
==8910== Command: ./a.out
==8910== 
abcbc
==8910== 
==8910== HEAP SUMMARY:
==8910==     in use at exit: 0 bytes in 0 blocks
==8910==   total heap usage: 1 allocs, 1 frees, 1,024 bytes allocated
==8910== 
==8910== All heap blocks were freed -- no leaks are possible
==8910== 
==8910== For lists of detected and suppressed errors, rerun with: -s
==8910== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
user786
  • 3,902
  • 4
  • 40
  • 72
  • 1
    valgrind doesn't always show such errors, especially if the buffer is on the stack and the overwrite is by a small amount. Try compiling with gcc -fsanitize=address (instead of using valgrind or in addition to it). – n. m. could be an AI Oct 12 '21 at 08:16
  • @n.1.8e9-where's-my-sharem. `gcc req.c -fsanitize=address` does not print anything either. what is ` -fsanitize` and `address`? – user786 Oct 12 '21 at 08:22
  • 1
    Compiling with `gcc -O2`: _/usr/include/x86_64-linux-gnu/bits/string_fortified.h:29:10: warning: ‘__builtin___memcpy_chk’ writing 3 bytes into a region of size 2 overflows the destination_ – David Ranieri Oct 12 '21 at 08:22
  • @DavidRanieri can u please tell what is this `-O2` flag its really good – user786 Oct 12 '21 at 08:27
  • 1
    It enables optimization, there are four levels of optimization on gcc, from `-O0` to `-O3`, `-g` is suggested for debug while `-O2` is suggested for release versions. – David Ranieri Oct 12 '21 at 08:29
  • https://coliru.stacked-crooked.com/a/2af46bfa137e5609 – n. m. could be an AI Oct 12 '21 at 08:32

0 Answers0