Char array can hold more than expected

后端 未结 3 1472
猫巷女王i
猫巷女王i 2021-01-17 06:58

I tried to run this code in C and expected runtime error but actually it ran without errors. Can you tell me the reason of why this happens?

char str[10];
sc         


        
3条回答
  •  难免孤独
    2021-01-17 07:44

    This is a good question. And the answer
    is that it there is indeed a memory problem
    The string is read and stored from the address of str
    up until the length of the actual read string demands,
    and it exceeds the place you allocated for it.

    Now, it may be not crash immediately, or even ever for
    short programs, but it's very likely that when you expand
    the program, and define other variables, this string will
    overrun them, creating weird bugs of all kinds, and it may
    eventually also crash.

    In short, this is a real error, but it's not uncommon to have
    memory bugs like this one which do not affect at first, but
    do create bugs or crash the program later.

提交回复
热议问题