I was expecting a segfault with this code:
char * foo (char my_ascii[10])
{
strcpy (my_ascii, "0123456789");
return my_ascii;
}
char bar[2];
printf("%s\n", foo (bar));
Because bar reserves a 2-char array in the stack, and foo() tries to write 10 chars. However, printf() writes in stdout 10 chars and errors don't occur. Why is this happening?
Additionally, if I modify the foo() function this way:
char * foo (char my_ascii[1])
{
strcpy (my_ascii, "0123456789");
return my_ascii;
}
The behaviour is exactly the same: 10 chars are copied to my_ascii. Any explanation?
Thank you very much in advance.
char * foo (char my_ascii[10])
andchar * foo (char my_ascii[1])
are both equivalent tochar * foo (char *my_ascii)
Note: An array type decays into a pointer(to the first element of the array) type when passed to a function.
That's because undefined behaviour means anything can happen.
Just for the record