Memory confusion for strncpy in C

后端 未结 4 1743
花落未央
花落未央 2021-01-13 14:45

This week one problem was discussed by my colleague regarding memory:

Sample code 1:

int main()
{
    #define Str \"This is String.\"
    char dest[1         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-13 15:31

    strncpy(dest, Str, sizeof(Str));

    Your dest is only one byte, so here you are writing in memory which you are not supposed to and this invokes undefined behavior. In other words, anything can happen depending on how compiler implement these things.

    The most probable reason for buf getting written is that the compiler places dest after buf. So when you are writing past the boundary of dest you are writing to buf. When you comment out buf it leads to crash.

    But as I said before, you may get completely different behavior if a different compiler or even different version of same compiler is used.

    Summary: Never do anything that invokes undefined behavior. In strncpy you are supposed to use sizeof(dest), not sizeof(src) and allocate sufficient memory for destination so that data from source is not lost.

提交回复
热议问题