The behavior of the C language character array is too mysterious

Even if you pack a character string longer than the length declared in the char array, it will work normally.

I wonder why ...

Environment: gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-4)

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

int main()
{
    char s[2];
    strcpy(s, "very long long string");
    printf("%s\n", s);
    printf("strlen = %d\n", (int)strlen(s));
    printf("size = %d\n", (int)sizeof(s));
    return 0;
}

Execution result

very long long string
strlen = 21
size = 2

Recommended Posts