-1

So I tried to make easy alloc and then free allocated memory but valgrind writes these errors.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{

  char* area=(char*)malloc(3);
  strcpy(area, "lal");
  printf("%s\n",area);
  free(area);

return 0;
}

Invalid write of size 4
==2728==    at 0x10873A: main (in /home/david/po1/a.out)
==2728==  Address 0x5200040 is 0 bytes inside a block of size 3 alloc'd
==2728==    at 0x4C2CB3F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==2728==    by 0x108731: main (in /home/david/po1/a.out)
==2728== 
ewazdomu
  • 39
  • 5

1 Answers1

2

In C, strings all end with the null terminator, which is a single 0x00 byte. This is automatically added to the end of all string literals, so when you copied "lal" into area, you were actually copying 4 bytes, 'l', 'a', 'l' & '\0' to area, which is why Valgrind complained.

Always make sure you have enough room for the null terminator whenever you are dealing with C strings!

Randy the Dev
  • 25,810
  • 6
  • 43
  • 54
  • 1
    this is especially true when a string is enclosed in double quotes, such as where he did `strcpy( area, "lal" );` – ron Nov 12 '16 at 01:14
  • `strcpy()` will actually always copy the null terminator, as it uses the null terminator to know when to stop copying! It's for this reason that using `strcpy()` is generally considered to be unsafe. – Randy the Dev Nov 12 '16 at 01:16
  • 1
    @AndrewDunn it's perfectly safe if you check the length first or otherwise know the length – M.M Nov 12 '16 at 01:29
  • @AndrewDunn What is your preferred safer alternative to `strcpy()`? – chux - Reinstate Monica Nov 12 '16 at 02:41
  • `strcpy_s()` was added to the C standard that requires you specify the size of the destination buffer. This will ensure that extra bytes will not be written to the destination buffer if they won't fit. Generally speaking, an unchecked `strcpy()` to a buffer on the stack is game over from a security standpoint. – Randy the Dev Nov 12 '16 at 03:00