-2

I have the following code:

  char buf[10];
  strcpy(buf, "This is a string longer than way longer than ten characters.");
  printf("%s\n", buf);  

I know that the second line will result in a segfault as I'm writing past the length of the array buf, as I get the following:

  ./a.out
  This is a string longer than way longer than ten characters.
  Segmentation fault (core dumped)

How come the printf command is executed as strcpy gives a segfault? I ran without the print statement and I get only a segfault.

tj56
  • 162
  • 3
  • 12
  • 1
    It's undefined behaviour. There's no reason to expect *when* it should segfault (if at all). – P.P Mar 29 '18 at 09:12
  • You know wrong. The stack is big enough to accomodate for your string, but you overwrite quite some upper stack frames and return addresses, that's why it segfaults on return. – Joker_vD Mar 29 '18 at 09:15

1 Answers1

0

Coding in C, you can go after the size of you array. you will use memory that is not dedicated to your variable. You can use it without any problem but remember that this "free" memory can be allocated to any variable you might use/declare after ! That's why the only 'protected' part of your string will be the 10 first chars because you declared it

Not Ultiko
  • 33
  • 7