why the string is getting altered after strcat()?

前端 未结 4 674
一向
一向 2021-01-27 22:20

this is the source code

int main()
{
    char str[]=\"dance\";
    char str1[]=\"hello\";
    char str2[]=\"abcd\";
    strcat(str1,str2);
    printf(\"%s\",s         


        
4条回答
  •  滥情空心
    2021-01-27 22:51

    This is a "Undefined behavior"

    str, str1, str2 have a limited size, and they are putted in the stack, the sequence depends on the compiler. You probably have something like this in your stack.

    ['a']['b']['c']['d']['\0']['h']['e']['l']['l']['o']['\0']['d']['a']['n']['c']['e']['\0']

    Got it?

    When you writes after the initial size of str1, you are overriding the stack, an changing all others variable that are on the stack.

提交回复
热议问题