Memory confusion for strncpy in C

后端 未结 4 1741
花落未央
花落未央 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:09

    This is an interesting problem that we all wish to understand at some point or the other. The problem that occurs here is known as “Buffer Overflow”. The side effects of this problem can vary from system to system (also referred as undefined behavior). Just to explain you what might be happening in your case lets assume that the memory layout of the variables in your program is as below

    Note above representation is just for understanding and doesn't show actual representation for any architecture. After the strncpy command is executed the contents of this memory region are as below

    Now when you print buff you can see that the start address of buf now has 'h' in it. The printf starts printing this until it finds a null character which is past the buff memory region. Hence you get 'his is String' when you print buf. However note that program 1 doesn't generate a stack smashing error because of stack guard (which is system/implementation) dependent. So if you execute this code on a system that doesn't include this the Program 1 will also crash (You can test this by increasing Str to a long string).

    In case of Program 2 the strncpy just goes past the stack guard over writing the return address from main and hence you get a crash.

    Hope this helps.

    P.S. All above description is for understanding and doesn't show any actual system representation.

提交回复
热议问题